Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 3[0] and 3[1] results in 1 in Ruby?

It's very interesting that integers can access indexes like and array.

So we can make things like this:

puts 3[0] returns 1.

puts 3[1] returns 1.

puts 3[2] returns 0.

What is all about that?

like image 681
Caco Avatar asked Nov 28 '25 02:11

Caco


1 Answers

From the docs for Integer#[]:

Bit Reference---Returns the nth bit in the binary representation of int, where int[0] is the least significant bit.

3 is 11 in binary, so 3[0] (the least significant one) and 3[1] are 1 and everything else is 0.

like image 112
Ursus Avatar answered Nov 30 '25 17:11

Ursus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!