Ruby 2.0.0: Keyword Arguments with Hash as first argument

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.

I think this behaviour was already logged as a bug:
https://bugs.ruby-lang.org/issues/8316#change-38850

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs