0

Is there an expression in Ruby equivalent to JavaScript's for:

myHash[id] = myHash[id] || {};

This is usually used when trying to append an array or hash to an existing one but we don't know if it was already created or is the first iteration.

the Tin Man
161k44 gold badges222 silver badges308 bronze badges
asked Mar 7, 2017 at 18:39
3
  • Don't know Ruby, but wouldn't just it's logical OR work? Does it return a boolean value or the first truthy value? Commented Mar 7, 2017 at 18:43
  • 2
    myHash[id] ||= {} is the equivalent Commented Mar 7, 2017 at 18:43
  • Please do not use salutations like "hi", valedictions ("thanks!") or signatures. Stack Overflow is not a discussion list, it's an online reference. Also, grammar, spelling and punctuation are all significant. Commented Mar 7, 2017 at 22:56

2 Answers 2

2

In Ruby, this code actually works the same as in JavaScript:

myHash[id] = myHash[id] || {}

That being said, the more eloquent way of doing it is:

myHash[id] ||= {}
the Tin Man
161k44 gold badges222 silver badges308 bronze badges
answered Mar 7, 2017 at 18:44
Sign up to request clarification or add additional context in comments.

Comments

0

While these are equivalent:

my_hash[:id] = my_hash[:id] || {} 
my_hash[:id] ||= {} 

You'll find this useful:

require 'fruity'
my_hash = {}
compare do
 test1 { my_hash[:id] = my_hash[:id] || {} }
 test2 { my_hash[:id] ||= {} }
end
# >> Running each test 32768 times. Test will take about 1 second.
# >> test2 is faster than test1 by 2x ± 0.1

Between the two, the second, test2, is idiomatic Ruby, so, while the difference in speed is slight, it adds up. It's also the Ruby way.

answered Mar 7, 2017 at 22:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.