Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bracket notation on Ruby numbers

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?

like image 464
tckmn Avatar asked Mar 29 '13 00:03

tckmn


People also ask

What do brackets mean in Ruby?

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.

What do square brackets mean in Ruby?

Square brackets indicate character classes in Ruby regular expressions.


1 Answers

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

like image 56
Peter Avatar answered Sep 21 '22 23:09

Peter