[ruby-core:94480] [Ruby master Feature#16115] Keyword arguments from method calls or ignore extra hash keys in splat
From:
kimmo.lehto@...
Date:
2019-08-22 12:01:33 UTC
List:
ruby-core #94480
Issue #16115 has been reported by kke (Kimmo Lehto).
----------------------------------------
Feature #16115: Keyword arguments from method calls or ignore extra hash keys in splat
https://bugs.ruby-lang.org/issues/16115
* Author: kke (Kimmo Lehto)
* Status: Open
* Priority: Normal
* Assignee:
* Target version:
----------------------------------------
Just a thought, feel free to insta-close as stupid.
Currently you can do this:
```
def hello(who:)
puts "Hello, #{who}"
end
opts = { who: 'world' }
hello(who)
```
Or:
```
def hello(who:, **_extra_opts) # without eating extra args, you get ArgumentError (unknown keyword: foo)
puts "Hello, #{who}!"
end
hello(**{ who: 'world', foo: 'bar' })
```
Or even this:
```
def hello(_obj = nil, who: _obj&.who || raise(ArgumentError, "missing who:"))
puts "Hello, #{who}!"
end
hello(OpenStruct.new(who: 'world'))
```
1) What if when you passed an object as an argument to a method that only accepts keyword arguments, the methods listed would be called? Then you could do:
```
require 'ostruct'
ostruct = OpenStruct.new(who: 'world, foo: 'bar')
def hello(who:)
puts "Hello, #{who}!"
end
hello(ostruct)
```
2) Or perhaps add some sort of "triple splat" that would either a) do the method calling thing described above or b) do the regular hash splatting like `**` but ignore any keys present that are not listed as keyword arguments:
```
require 'ostruct'
ostruct = OpenStruct.new(who: 'world', foo: 'bar')
def hello(who:)
puts "Hello, #{who}!"
end
# a:
hello(***ostruct) # would call ostruct.who to figure out `who:`
# or b: (currently with ** raises ArgumentError (unknown keyword: foo))
hello(***{ who: 'world', foo: 'bar' }) # would ignore any extra keys
```
I think this could open up some possibilities (or a can of worms).
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>