Neil Neil - 3 months ago 13
Ruby Question

Understanding Implicit hash within a ruby method definition

I was watching the CooperPress Youtube video that discusses different ways to specify arguments with defaults within a method definition.

He discusses how in Ruby 2.0 there is some syntactic sugar which allows you to specify an implicit hash that also sets default values for each

key
within this hash. Located at this part of the video, but I will redisplay the code below:

def some_method(x: 10, y: 20, z: 30)
puts x
puts y
puts z
end

some_method x: 1, y: 2

=> 1
=> 2
=> 30


What I am having trouble understanding is why turning that implicit hash into an explicit hash doesn't work. Basically: all I am doing is putting curly braces around that implicit hash argument within the method definition. As I see it: putting curly braces around the key/values is just a more explicit way to say that a hash wraps those key/values and it should have the exact same behavior. However, when I do this it errors out:

def some_method({x: 10, y: 20, z: 30}) #curly braces here
puts x
puts y
puts z
end

some_method x: 1, y: 2

=> rb:1: syntax error, unexpected {, expecting ')' def some_method({x: 10, y: 20, z: 30})


Question: Why does turning that implicit hash argument within the method definition into an explicit hash argument make the method error out?

Answer

Haven't watched that video, but "implicit hash" is a poor choice of words. This is a feature called "keyword arguments" and it has a pretty specific syntax which, yes, resembles a hash, but isn't one.

For example, it allows required arguments, which is impossible in a hash.

def foo(required:, optional: 1)
  # some code
end