ruby-on-railsrubyhashmultiple-assignment

Is it possible to use parallel assignment for keys in Ruby hash?


Given that it is an immutable object, ruby allows paraller assignments as this:

sample[:alpha] = sample[:beta] = sample[:gamma] = 0

But is there any other simple way to do this? , something like :

sample[alpha:, beta:, gamma: => 0]

or:

sample[:alpha, :beta, :gamma] => 0, 0, 0 

Solution

  • Firstly, this does not work as you expect:

    sample = {}
    sample[:alpha], sample[:beta], sample[:gamma] = 0
    

    This will result in:

    sample == { alpha: 0, beta: nil, gamma: nil }
    

    To get the desired result, you could instead use parallel assignment:

    sample[:alpha], sample[:beta], sample[:gamma] = 0, 0, 0
    

    Or, loop through the keys to assign each one separately:

    [:alpha, :beta, :gamma].each { |key| sample[key] = 0 }
    

    Or, merge the original hash with your new attributes:

    sample.merge!(alpha: 0, beta: 0, gamma: 0)
    

    Depending on what you're actually trying to do here, you may wish to consider giving your hash a default value. For example:

    sample = Hash.new(0)
    
    puts sample[:alpha] # => 0
    sample[:beta] += 1  # Valid since this defaults to 0, not nil
    
    puts sample         # => {:beta=>1}