How do methods use hash arguments in Ruby?

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.

Leave a Comment