I found that when using bracket notation on the number 100
in Ruby, I get this:
irb(main):001:0> 100[0]
=> 0
irb(main):002:0> 100[1]
=> 0
irb(main):003:0> 100[2]
=> 1
So I assumed it was getting the digits, indexed like this:
NUMBER: 1|0|0
-----
INDEX: 2|1|0
I tried this on the 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 would expect it to return 9
, then 8
, then 7
if it was getting the digits. From this result, that is clearly not happening, so what exactly does using bracket notation on a number do?
The square brackets [ ] are used to initialize arrays. The documentation for initializer case of [ ] is in ri Array::[] The curly brackets { } are used to initialize hashes.
Square brackets indicate character classes in Ruby regular expressions.
These are the binary bits that you're pulling off. Another way to see this is using to_s
with an argument indicating the desired base.
>> 789.to_s(2)
=> "1100010101"
String indexing is from left-to-right, so you can't compare []
on the string, but note how (from right-to-left) the digits are 1, 0, 1.
Here's the docs if you're interested: http://ruby-doc.org/core-1.9.3/Fixnum.html#method-i-5B-5D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With