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
}