NilClass improvement

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)

I tried def [*arg] but not accepted

class NilClass
def
self
end
end

I tried def [*arg] but not accepted

The ruby parser wants to have the [] before
the argument.

def

Same on class-method level:

def self.
def self.

thanks
done and working as expected :slight_smile:

class NilClass
def
self
end
end

Your NilClass.merge! does not set/assign anything, just returns its
argument or nil.

Just don’t try reinvent a wheel. Ruby’s Hash supports so called “default
value” and it can be used for such task. See `Hash.new’ in docs for
details.

As you probably won’t share this value across elements, block version of
constructor should be used, as it always creates new value placeholder:

my_hash = MyHash.new { |h,k| h[k] = {} }

then

my_hash[:tres].merge!({c:3, d:4, e:5})

would work as expected, using #merge! of new created hash placeholder.

Let’s do it even further…
let’s guess we are doing something like that:

my_hash={uno: {a: 1, b: 2}, dos: {z:9, y:8}}

my_hash[:uno].merge!({c:3, d:4, e:5})

This works very well… but what about if want to do something like this

my_hash[:tres].merge!({c:3, d:4, e:5})

it will say that ‘merge’ method doesn’t exist for nil class
so i defined it:

class NilClass
def merge!(hash_to_merge)
if hash_to_merge.kind_of?(Hash) then
hash_to_merge
else
nil
end
end
end

and it works… but actually it is not assigned to my_hash[:tres]

puts my_hash.inspect returns:
{:uno=>{:a=>1, :b=>2, :c=>3, :d=>4, :e=>5}, :dos=>{:z=>9, :y=>8}}

so no :tres key
but puts my_hash[:tres].merge!({c:3, d:4, e:5}) returns what is
expected:
{:c=>3, :d=>4, :e=>5}

but it is not assigned… how can i do it?

thanks.

Thanks a lot exactly what i need it :slight_smile: