Saturday, April 13, 2013

Surprising things in Ruby #1

Try this in your irb:
irb(main):001:0> def foo
irb(main):002:1>   'hello world'
irb(main):003:1>   end
=> nil
irb(main):004:0> 'a'.foo
=> "hello world"
If you're not used to Ruby, this may seem surprising. This may help make it clearer:
irb(main):006:0> method(:foo)
=> #<Method: Object#foo>
The "method" function takes a symbol and returns a reference to that method. That allows you to do cool things like this:
irb(main):013:0> a = method(:foo)
=> #<Method: Object#foo>
irb(main):014:0> a.call
=> "hello world"
... but it also in this case tells us where the method is defined. The method "foo" is defined directly on the Object class. When you create an otherwise anonymous function, that's where it goes. And since almost everything in Ruby derives from the Object class, you've just defined the "foo" method for all those things.

I haven't been able to find anything that describes why this is the case, but it's a hard question to ask Google. I keep getting pointed at Ruby primers, which don't go into nearly enough detail. It seems like it would be a result of the "everything is a first-class object" nature of Ruby - a random function might violate that principle? I'm not sure.

If anybody knows what the reasoning behind this is, I'd like to hear about it.


No comments:

Post a Comment