Example:
def foo(regular, hash={})
puts "regular: #{regular}"
puts "hash: #{hash}"
puts "a: #{hash[:a]}"
puts "b: #{hash[:b]}"
end
foo("regular argument", a: 12, :b => 13)
I use hash={}
to specify that the last argument is a hash, with default value of empty hash. Now, when I write:
foo("regular argument", a: 12, :b => 13)
It's actually a syntactic sugar for:
foo("regular argument", {a: 12, :b => 13})
Also, {a: 12}
is syntactic sugar for {:a => 12}
.
When all of this is combined together, you get a syntax that looks similar to named arguments in other languages.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…