Reputation: 337
Lately I saw this function signature:
class Foo < Bar
def initialize(arg: {})
...
end
What does the keyword argument (arg: {}
) with the curly braces means here?
Upvotes: 3
Views: 801
Reputation: 101811
Its just a keyword argument with an empty hash as the default value:
def initialize(arg: {})
arg
end
irb(main):011:0> initialize().class
=> Hash
Its really strange and unidiomatic though. Before Ruby 2.0 introduced first-class support for keywords you declared a method that takes an optional options hash as:
def initialize(hash = {})
end
This argument had to be at the end of the list of. The name is not significant.
With Ruby 2.0 you can declare a method that takes any number of keywords with a double splat:
def initialize(**other_keyword_args)
end
You can combine it with positional and named keyword arguments as well:
def initialize(a, b = 2, foo:, bar: 2, **other_keyword_args)
end
Using initialize(arg: {}, ...)
would make sense if there where more parameters and this one takes a hash but on its own its just strange.
Upvotes: 3
Reputation: 160551
Ruby doesn't need braces ({}
) around a hash when passing the last argument to a method:
def foo(anything)
anything # => {:arg=>{}}
.class # => Hash
end
foo(arg: {})
For more information see "Calling Methods."
Upvotes: -1