Designating Brackets by Ruby Numbers

I found that when using the notation in brackets of the number 100 in Ruby, I get the following:

 irb(main):001:0> 100[0] => 0 irb(main):002:0> 100[1] => 0 irb(main):003:0> 100[2] => 1 

So, I assumed that it gets the numbers indexed as follows:

 NUMBER: 1|0|0 ----- INDEX: 2|1|0 

I tried this on number 789 with unexpected results.

 irb(main):004:0> 789[0] => 1 irb(main):005:0> 789[1] => 0 irb(main):006:0> 789[2] => 1 

I expect it to return 9 , then 8 , then 7 if it gets numbers. This clearly does not happen from this result, so what does it mean that using notation in the form of brackets on a number does?

+7
source share
1 answer

These are the binary bits that you shoot. Another way to see this is to use to_s with an argument indicating the desired base.

 >> 789.to_s(2) => "1100010101" 

The strings are indexed from left to right, so you cannot compare [] with a string, but note how (from right to left) the numbers 1, 0, 1.

Here are the documents if you are interested: http://ruby-doc.org/core-1.9.3/Fixnum.html#method-i-5B-5D

+13
source

All Articles