I’m trying to get rid of error messages like this one:
: undefined method `[]’ for nil:NilClass (NoMethodError)
when in a comparation where we are supposed to get some array/hash we
don’t get any… so actually the comparation should return ‘false’
So I want to improve the NilClass by adding a [(arg)] method that can
manage this situation but for the moment all i could do is to add the
method [], I don’t know how to add a [xxxx] method
So let’s think we have this piece of code:
a=nil
puts a[5]==“mario”
this will return
undefined method `[]’ for nil:NilClass (NoMethodError)
I know i could use
puts a.kind_of?(Array) && a[5]==“mario”
puts !a.nil? && a[5]==“mario”
but I’m trying to simplify the process and by not being necessary to add
that for every comparison
so if i want it to return false by itself, if i modify the NilClass like
this:
class NilClass
def []
false
end
end
it will return false if i try to compare:
puts a[]==“mario”
but if I try to compare
puts a[5]==“mario”
it returns:
wrong number of arguments (1 for 0) (ArgumentError)