Dwarakanath Thoppe
Dwarakanath Thoppe

Reputation: 167

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 

Upvotes: 1

Views: 1476

Answers (3)

Tom Lord
Tom Lord

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

Shobhit
Shobhit

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

Ursus
Ursus

Reputation: 30071

What about this one?

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

Upvotes: 1

Related Questions