Reputation: 5178
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?
Upvotes: 0
Views: 786
Reputation: 230461
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
Upvotes: 2
Reputation: 87486
There are special syntax rules for what you can write in a method argument definition, you cannot just write arbitrary expressions.
You could write this:
def foo(opts = arbitrary_hash)
That would mean the method has one argument and its default value is whatever arbitrary_hash
is, but that would be an unusual way to do it because then if you pass any argument to the method, none of the defaults get applied.
Upvotes: 1