Topic: Incrementing or setting a value

Is there a short hand way of doing this:

if hash[ele[1]].nil?
  hash[ele[1]] = 1
else
  hash[ele[1]] += 1
end

Re: Incrementing or setting a value

As far as I understood, in your example you are checking if a Hash key is not nil? If it is the case, I'd rather check it with 'has_key?' method:

if my_hash.has_key?(a_key)
   ...your stuff here
end

Re: Incrementing or setting a value

If your hash is only being used to store integers you could have it so the default value for a missing key is 0. Then you can +1 without worrying about it.

Rob Anderton
TheWebFellas

Re: Incrementing or setting a value

my_hash[ele[l]] ||= 0
my_hash[ele[l]] += 1

Re: Incrementing or setting a value

@counter = @counter.nil? ? 0 : @counter += 1

Use ternary for one-liner.  I was also seeing if there was another way to do this, the above was the best I could come up with.

[ I know this is an old post, but it comes up high in search results. ]

Re: Incrementing or setting a value

How about:
hash[ele[1]] = hash[ele[1]].to_i + 1

(If nil, nil.to_i == 0)