Search code examples
rubyruby-hash

Why am I unable to edit the values in this hash?


I'm trying to create a new hash called $player[:abil_mods] which is based on my $player[:abils] hash. It should take each value, subtract 10, divide by 2, and assign it to an identical key in the new hash. However, it doesn't seem to be editing the values in $player[:abil_mods].

My code:

$player = {
  abils: {str: 20, con: 20, dex: 14, wis: 12, int: 8, cha: 8},
  abil_mods: {}
}

$player[:abil_mods] = $player[:abils].each { |abil, pts| ((pts - 10) / 2).floor }

should create the following $player[:abil_mods] hash:

abil_mods: {str: 5, con: 5, dex: 2, wis: 1, int: -1, cha: -1}

but it is instead creating:

abil_mods: {str: 20, con: 20, dex: 14, wis: 12, int: 8, cha: 8}

Solution

  • The problem is that in the line

    $player[:abil_mods] = $player[:abils].each { |abil, pts| ((pts - 10) / 2).floor }
    

    you are assigning the return value of the method Hash#each that is self to the the Hash $player at key :abil_mods. In your case the Hash is referenced by $player[:abils].

    You could use Enumerable#map which returns an array that can be easily converted to a hash:

    $player[:abil_mods] = $player[:abils].map { |k, pts| [k,  ((pts - 10) / 2).floor] }.to_h