September 2, 2007 at 11:41 pm
· Filed under Ruby, Ruby Mailing List, irb
Recently a user by the name of 7stud has been asking questions about Hash on comp.lang.ruby. In some curiosity fueled by his, I was playing around with this:
class Hash
alias_method :old_get, '[]'
def [](key)
puts "#{key} => #{old_get(key)}"
old_get(key)
end
end
I was expecting little more than (assuming a = {:b => ‘c’}):
003:0> a[:b]
b => c
"c"
But what I got (besides a whole bunch of irb config values and Wirble related output) included this:
a =>
a =>
[ => #<IRB::SLex::Node:0x13dce34>
: =>
: => #<IRB::SLex::Node:0x13dd514>
b =>
b =>
b =>
] => #<IRB::SLex::Node:0x13dd6cc>=>
] => RubyToken::TkRBRACK
=> #<IRB::SLex::Node:0x13df7b0>
It’s too late on a Sunday to look further, but it’s nice to see how much is right there for the gleaning.
Permalink
July 7, 2007 at 8:02 pm
· Filed under Ruby, Ruby Mailing List
Someone over at comp.lang.ruby asked for a way to find out which modules had been included in a class. I guessed that the ancestors method (defined in the Module class) would be the key, and that Array’s select would be the… other key… Huh. Anyway, this does it (assuming a class C):
C.ancestors.select {|a| a.class == Module}
I even posted it as a solution. But what I should have looked closer, because there is exactly a method that does it, and it’s sort of obvious:
C.included_modules
Of course, I don’t know the Module methods by heart, and I had just assumed that he had already looked for something in the documentation.
Moral of the story: Never assume a person asking a question has even so much as tried anything out on irb or looked at the documentation.
Bonus moral: Matz names everything what you would name it (pretty much). You can guess at Ruby methods and get it right an awful lot.
Permalink