This post originated from an RSS feed registered with Ruby Buzz
by Jan Lelis.
Original Post: The 28 Bytes of Ruby Joy!
Feed Title: rbJ*_*L.net
Feed URL: http://feeds.feedburner.com/rbJL
Feed Description: Hi, I am a fan of Ruby and like to explore it and the world around ;).
So I started this blog, where I am publishing code snippets, tutorials for beginners as well as general thoughts about Ruby, the web or programming in general.
All it does is patching the nil object that it also returns nil when you call an unknown method on it. Normally it would raise a NoMethodError. This is the cleaner, non-golfed version:
Consider the following, common situation: You have an instance variable, which usually contains a hash of objects: @some_hash. Now you want to access :some_key and want to do something with the value. You also know, @some_hash is sometimes nil. So you might want to write
if @some_hash[:some_key] # good looking version
# do something with @some_hash[:some_key]
end
but it is not working properly, because it fails on when @some_hash is nil. Instead, you have to write
if @some_hash && @some_hash[:some_key] # correct version
# do something with @some_hash[:some_key]
end
And this is just an easy example. Let’s take a look at
if @some_hash[:some_key].to_formatted_array[3] # good looking version
# do something
end
vs
if @some_hash && some_hash[:some_key] && @some_hash[:some_key].to_formatted_array && @some_hash[:some_key].to_formatted_array[3] # correct version
# do something
end
The 28 Bytes of Ruby Joy allow you to do use the good looking version in both examples.
Conclusions
A drawback of the hack might be, that the application does not crash at some occasions, where it probably should do so, but forwards the nil. But I think, in reality, this means just a few more tests.
The primary reason, I dislike the exception raising of nil is that it creates some kind of redundancy. I do not want to double-check if something is nil. And to say it with the words of Yukihiro Matsumoto himself: “When information is duplicated, the cost of maintaining consistency can be quite high.”
So, what is a strong counter-argument for not using the28 Bytes of Ruby Joy?