Is there a shorter way to change the value of a key?
my_array.each do |x|
if my_hash.key?(x)
my_hash[x] += 1
else
my_hash[x] = 1
end
end
Is there a shorter way to change the value of a key?
my_array.each do |x|
if my_hash.key?(x)
my_hash[x] += 1
else
my_hash[x] = 1
end
end
In your specific case it's probably easiest to give the hash a default value:
my_hash = Hash.new(1)
=> {}
my_hash[:x]
=> 1
my_hash[:y] += 1
=> 2
Please note that this only makes sense if the default value is immutable, otherwise the reference will be shared between all keys.
You can use the ternary operator to write your statement on one line.
my_array.each {|x| my_hash.key?(x) ? my_hash[x].next : my_hash[x] = 1}
You can also use the next method if you are increasing a value by just 1.