Is it okay to define a [] method in ruby's NilClass?
- by Silasj
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?