Reputation: 167
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
Upvotes: 1
Views: 1476
Reputation: 28305
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}
Upvotes: 4
Reputation: 647
There is nothing like the thing you've described but you can run a loop with all the and assign the value.
keys = [:alpha, :beta, :gamma, :theta, ...]
keys.each {|key| sample[key] = 0}
Reduces the number of extra keystrokes, and very easy to change the keys array.
Upvotes: 0