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
Giancarlo Benítez
4381 gold badge4 silver badges19 bronze badges
2 Answers 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
eiko
5,3956 gold badges21 silver badges36 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
the Tin Man
161k44 gold badges222 silver badges308 bronze badges
Comments
default
myHash[id] ||= {}is the equivalent