1

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
Incerteza
  • 32,326
  • 47
  • 154
  • 261

3 Answers3

1

A bit shorter:

my_array.each do |x| 
  my_hash[x] ||= 0
  my_hash[x] += 1
end
Thomas
  • 1,613
  • 8
  • 8
1

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.

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
0

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.

Darkmouse
  • 1,941
  • 4
  • 28
  • 52