Sunday, June 17, 2007

More Stupid Ruby Tricks: has_key("hell")

What is missing from the title. The bloody question mark! It serves me right for trying to code when fried from various domestic chores. The "undefined method" exception (like many cryptic Ruby error messages) wasn't terribly helpful either, or at least in my reduced state of competency, but maybe blogging on it will get it through my thick skull that method names that return booleans have a question mark suffix. I really don't see the point. How many (I'm sure some smartass will say TCL or some happy-ass functional language I could care less with that starts with an H or L) other languages have this idiom that confuses idiots. This seems seems unnecessary and certainly violates the "principle of least surprise" or perhaps I'm misapplying the term.
irb(main):003:0> d = {}
=> {}
irb(main):004:0> d[0] = 1
=> 1
irb(main):005:0> d[5] = 2
=> 2
irb(main):006:0> d
=> {5=>2, 0=>1}
irb(main):008:0> d.has_key(5)
NoMethodError: undefined method `has_key' for {5=>2, 0=>1}:Hash
from (irb):8
from :0
irb(main):009:0> d.has_key?(5)
=> true


Jim said...

One thing that I like to do when I absolutely know something should exist is to do something like

m = chunk.methods.sort!

where chunk is whatever the object you're messing with is. This throws an array of strings that ruby knows about into m. The sort! is just for shits and giggles to make things way more readable. The .methods method alone is helpful and if the bang (!) syntax on sort isn't too much of a stretch coming from other languages then that's straightforward too. I come from a heavy C background but wasn't too tripped up on it, YMMV.

Don't worry - I don't represent the ruby community, so you're safe from not hating this comment:)

Matt Franz said...

Thanks, your refinement of .methods makes it as useful dir(object) in Python, which (of course!) is already sorted! But now that I've stopped doing anything in Python the little "close, but no cigar" syntactical differences are tripping me up less often and there is less to hate...