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
endYou are not logged in. Please login or register.
Rails Forum - Ruby on Rails Help and Discussion Forum » Ruby Programming » 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
endAs 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
endIf 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.
my_hash[ele[l]] ||= 0
my_hash[ele[l]] += 1@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. ]
How about:
hash[ele[1]] = hash[ele[1]].to_i + 1
(If nil, nil.to_i == 0)
Hosting provided by aTech Media