Reputation: 438
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.
Upvotes: 0
Views: 376
Reputation: 160551
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.
Upvotes: 0
Reputation: 5345
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] ||= {}
Upvotes: 2