There are some little-known shortcuts for creating new hashes. They all provide a slightly different convenience. The latter two generate a hash directly from pre-existing key-value pairs. The first simply sets a default value for all elements in the hash. Let’s take a look at that first.
normal = Hash.new
was_not_there = normal[:zig]
puts "Wasn't there:"
p was_not_there
usually_brown = Hash.new("brown")
pretending_to_be_there = usually_brown[:zig]
puts "Pretending to be there:"
p pretending_to_be_there
Result:
Wasn’t there:
nil
Pretending to be there:
“brown”
As you can see, where a “normal” hash always returns nil by default, specifying a default in the Hash constructor will always return your custom default for any failed lookups on that hash instance.
Và
The other two shortcuts actually use the Hash class’s convenience method: Hash::[]. They’re fairly straight-forward. The first takes a flat list of parameters, arranged in pairs. The second takes just one parameter: an array containing arrays which are themselves key-value pairs. Whew! That’s a mouthful. Let’s try the first form:
chuck_norris = Hash[:punch, 99, :kick, 98, :stops_bullets_with_hands, true]
p chuck_norris
Result:
{:punch=>99, :kick=>98, :stops_bullets_with_hands=>true}