Forum: Ruby Ruby 2.0.0: Keyword Arguments with Hash as first argument

Eb56e6fa19ee55379e313367f049c1f9?d=identicon&s=25 Bryan R. (bryan_r)
on 2013-10-14 20:47
I'm not saying this is a bug, but I can't explain this behavior. I'm
just looking for an explanation. If a method accepts a hash as its first
argument, and then one or more keyword arguments (with default values)
after that, the behavior is confusing. Calling the method with only a
single hash results in an `unknown keyword` error. However, Calling the
method with a hash first, and then another hash for the keyword
arguments, works just fine.

GIST: https://gist.github.com/bricker/6979707

```
puts RUBY_VERSION
#=> "2.0.0"

def parameters(params={}, content_type: "text/html")
  puts params
  puts content_type
end

parameters({ query: "Ruby" })
#=> ArgumentError: unknown keyword: query

parameters({ query: "Ruby" }, { content_type: "application/json" })
#=> {:query=>"Ruby"}
#=> application/json

parameters({ query: "Ruby" }, {})
#=> {:query=>"Ruby"}
#=> text/html
```

Can someone point me to documentation for this behavior, or otherwise
explain why it happens this way? Thanks.
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2013-10-14 21:51
I think this behaviour was already logged as a bug:
https://bugs.ruby-lang.org/issues/8316#change-38850
Fa0f9fecf293ddbe3d0c64f6b4418440?d=identicon&s=25 Dan Rathbun (dan_rathbun)
on 2013-11-05 18:47
TRY:

def parameters(
  *positional_args,
  content_type: "text/html",
  another_keyword: 1,
  **extra_hash_args
)
  puts "positional_args : #{positional_args.inspect}"
  puts "content_type    : #{content_type.to_s}"
  puts "another_keyword : #{another_keyword.to_s}"
  puts "extra_hash_args : #{extra_hash_args.inspect}"
end
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.