What does the parenthesis operator for FixNum do in Ruby?

Coming from Python, I find the following behavior very surprising:

irb(main):211:0> x= 33
=> 33
irb(main):212:0> x[0]
=> 1
irb(main):213:0> x[1]
=> 0
irb(main):214:0> x[2]
=> 0

      

Is there any rationale / philosophy not to raise an error in this example?

+3


source to share


4 answers


You might be a little confused as to what this does internally, but that's okay when working with Ruby because it's not at all like other scripting languages. If you haven't used SmallTalk , this might sound crazy.

When Ruby sees the following code:

x = 6
x[1]

      

What it actually does is the following:

x.send(:[], 6) # Send :[] method call to x with arguments [ 6 ]

      

The object is x

free to interpret what it wants, and the behavior usually (though not always) defined by the class x

belongs if it x

is an ordinary instance.

In this case, it returns the bit at the given index equivalent x & (1 << 6) >> 6

.

Sometimes a method []

does several things:



string = "brackets"

# Retrieve a single character
string[1]
# => "r"

# Retrieve a substring
string[5,2]
# => "et"

# Perform a pattern match
string[/[^aeiou]+/]
# => "br"

      

This does some pretty crazy stuff too, since you can apply it to Proc as well:

fn = lambda { |x| x + 1 }

# Conventional (explicit) call
fn.call(2)
# => 3

# Square bracket method
fn[5]
# => 6

      

Since Ruby relies very heavily on Duck Typing , this means you can write a Proc to fill in where you would normally have a hash or an Array, and the method that gets your object is no wiser.

This is the flexibility to leave the value x[...]

for your own instance of the class x

up to you, which makes it quite powerful.

For example:

class Bracketeer
  def [](i)
    "%d brackets" % i
  end
end

bracketeer = Bracketeer.new

bracketeer[6]
# => "6 brackets"

      

This simple notation will often come in handy when you are trying to create a minimal interface for your class. In many cases, you can use something as simple as []

replacing what would be a more verbose method such as find_by_id

or cache_fetch

.

+4


source


The parenthesis operator gives you the nth bit of the binary representation:



http://ruby-doc.org/core-2.1.2/Fixnum.html#method-i-5B-5D

+5


source


Sure. You will find that the guide is sufficiently illuminating.

This returns the binary bit for the bit position value as zero or one.

+1


source


It returns the nth bit, which is rightfully observed by @msergeant.

This means that for the number 33, its binary representation is:

Index : [7][6][5][4] [3][2][1][0]
Bits  :  0  0  1  0   0  0  0  1

      

Which explains the output:

irb(main):212:0> x[0]
=> 1
irb(main):213:0> x[1]
=> 0
irb(main):214:0> x[2]
=> 0

      

+1


source







All Articles