How to change the values of a Hash?



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



  • 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 it Hash#each_key since I didn't need it value the Hash during the loop. If you are using, use Enumerable#each in this way:

    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 a 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 little more idiom

    You can use a shortcut to create an array of strings, https://stackoverflow.com/questions/1274675/what-does-warray-mean . It would be 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
    }
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2