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.
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.
myHash[id] ||= {}is the equivalent