+ 3

[Ruby] What's the value of a[0] and a[1]?

a = "3 Is the answer 4 Is not".to_i b = a[1] * a[0] + a[1] puts b*b

1st Dec 2021, 6:28 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
3 Réponses
+ 3
According to docs 1) str.to_i returns the result of interpreting leading characters in *str* as an integer. So value of *a* in your case would be 3 https://ruby-doc.org/core-3.0.3/String.html#method-i-to_i 2) The bracket operator gives you the nth bit of the binary representation. Binary representation of 3 is 0011, so as Rik Wittkopp pointed out, a[0] would be 1, a[1] would also be 1 and rest 0. http://ruby-doc.org/core-2.1.2/Fixnum.html#method-i-5B-5D Hence the resulting value in *b* is 2 and the output 4.
2nd Dec 2021, 1:09 AM
Arsenic
Arsenic - avatar
+ 2
a[0] = 1 a[1] = 1 I don't know why. Anything above a[2] = 0 Interesting question. Hopefully you can get a better answer than mine. Google, here I come
1st Dec 2021, 9:42 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Arsenic Awesome 😁👍
2nd Dec 2021, 1:23 AM
Rik Wittkopp
Rik Wittkopp - avatar