How to change the values of a hash?

1

I need a loop to change the values of this object

{
    [ "Begin", "Dom" ] => 0,
    [ "Begin", "Seg" ] => 8,
    [ "Begin", "Ter" ] => 10,
    [ "Begin", "Qua" ] => 30,
    [ "Begin", "Qui" ] => 20,
    [ "Begin", "Sex" ] => 1,
    [ "Begin", "Sáb" ] => 0,
    [ "Finish", "Dom" ] => 0,
    [ "Finish", "Seg" ] => 1,
    [ "Finish", "Ter" ] => 0,
    [ "Finish", "Qua" ] => 0,
    [ "Finish", "Qui" ] => 0,
    [ "Finish", "Sex" ] => 0,
    [ "Finish", "Sáb" ] => 0
}

I need to change the values 0,8,10,30,20 ...

How can I do this?

    
asked by anonymous 04.12.2017 / 22:01

1 answer

0

Modifying values

First store Hash in a variable

meu_hash = {
    [ "Begin", "Dom" ] => 0,
    [ "Begin", "Seg" ] => 8,
    [ "Begin", "Ter" ] => 10,
    [ "Begin", "Qua" ] => 30,
    [ "Begin", "Qui" ] => 20,
    [ "Begin", "Sex" ] => 1,
    [ "Begin", "Sáb" ] => 0,
    [ "Finish", "Dom" ] => 0,
    [ "Finish", "Seg" ] => 1,
    [ "Finish", "Ter" ] => 0,
    [ "Finish", "Qua" ] => 0,
    [ "Finish", "Qui" ] => 0,
    [ "Finish", "Sex" ] => 0,
    [ "Finish", "Sáb" ] => 0
}

Then create a loop to modify the values to whatever you want and you're done! See:

meu_hash.each_key do |key|
  meu_hash[key] = 5
end

I used Hash#each_key since I did not need value of Hash during the loop. If you're going to use it, use Enumerable#each like this:

meu_hash.each do |key, value|
  meu_hash[key] = value * 5
end

You can also opt for Enumerable#map , but I do not like this solution in Hash , since it does not modify or return Hash :

novo_hash = Hash[meu_hash.map {|key, value| [key, value * 5]}]

This form is pure because it does not affect meu_hash , creating a new instance.

Leaving the code a bit more idiomatic

You can use a shortcut to create an array of strings, %w or %W . It would look like this:

meu_hash = {
  %w[Begin Dom] => 0,
  %w[Begin Seg] => 8,
  %w[Begin Ter] => 10,
  %w[Begin Qua] => 30,
  %w[Begin Qui] => 20,
  %w[Begin Sex] => 1,
  %w[Begin Sáb] => 0,
  %w[Finish Dom] => 0,
  %w[Finish Seg] => 1,
  %w[Finish Ter] => 0,
  %w[Finish Qua] => 0,
  %w[Finish Qui] => 0,
  %w[Finish Sex] => 0,
  %w[Finish Sáb] => 0
}
    
05.12.2017 / 02:20