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
}