Ruby by default does not include the method [] for NilClass
For example, to check if foo["bar"] exists when foo may be nil, I have to do:
foo = something_that_may_or_may_not_return_nil
if foo && foo["bar"]
# do something with foo["bar"] here
end
If I define this method:
class NilClass
def [](arg)
nil
end
end
Something like that would make this possible, even if foo is nil:
if foo["bar"]
# do something with foo["bar"]
end
Or even:
if foo["bar"]["baz"]
# do something with foo["bar"]["baz"] here
end
Question: Is this a good idea or is there some reason ruby doesn't include this functionality by default?
EDIT July 2017: My core complaint was the unwieldy foo && foo["bar"] && foo ["bar"]["baz"] idiom required to access nested values when at any point the value may be nil. As of Ruby 2.3, Array#dig and Hash#dig exist, which addresses my concern. Now I can use the following idiom!
if foo && foo.dig("bar", "baz")
# do something
end
# Note that errors will still occur if a value isn't what you expect. e.g.
foo = { "a" => { "b" => "c" } }
foo && foo.dig("a", "b", "c") # raises TypeError: String does not have #dig method
foo = nilor otherwise referencedfoo, and you callif foo["bar"], you're going to get anUndefined Method Error. Undefined stuff isn't automatically nil. – KChaloux Oct 19 '12 at 19:41foohas been set somewhere. If it's undefined, you still have the issue. But by defining[], you have one less issue. – silasjmatson Oct 19 '12 at 19:43fooisnil, it will returnnil. I'm not seeing the issue. A developer would be able to see that the code inside the if isn't running, and a few more checks could determine a cause. – silasjmatson Oct 19 '12 at 22:24