@DarshanComputing began talking about making the code more Ruby-like, but here's how I would do the sample code in its entirety:
chickens = {}
chickens["Davison"] = "plucky"
chickens["Mortimer"] = "sullen"
chickens["Chauncey"] = "forlorn"
chickens.each do |name, mood|
puts "#{name}: #{mood}"
end
Using merge
is fine, but it's also verbose. You'll see a lot of Ruby programmers take the more simple path and add the key/value pair directly, rather than rely on a mutating method.
Using for
to loop over something is definitely not Ruby-like. Though the language supports it, its use is eschewed by Ruby developers consistently. The reason is, for name, mood ...
adds name
and mood
to the local variables, unlike each
which confines them inside the do
block. Littering the variable space with temporary variables is bad-form. For instance, after running the original code I can do:
[7] (pry) main: 0> name
"Chauncey"
[8] (pry) main: 0> mood
"forlorn"