1

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 
1
  • How many keys do you have? Commented Sep 19, 2017 at 14:20

3 Answers 3

4

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Since 0 is immutable, it's safe to use Hash.new(0)
Ah yep, I forgot that's valid too. Thanks @Stefan, I updated the answer.
1

What about this one?

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.