How to change the values of a Hash?

Asked

Viewed 326 times

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 that?

1 answer

0


Modifying the values

First store the 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 for whatever you want and ready! See:

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

I used the Hash#each_key since I didn’t need the value of Hash during the loop. If you are going to use, use the Enumerable#each thus:

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

You can also choose Enumerable#map, but I don’t like this solution in Hash, since it does not modify or return a Hash:

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

This form is pure by not affecting the meu_hash, creating a new instance.

Leaving the code a little more idiomatic

You can use a shortcut to create a string array, the %w or %W. 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
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.