4

I know that in Ruby 2.0 and later you can have keyword arguments, so that you can define a method like this:

def foo(inline_argument, *args, **kwargs, &block)
  puts 'bar'
end

However, I was wondering: is there a built-in method which makes use of keyword arguments?

4

1 回答 1

3

cd编辑到我的 Ruby 安装目录并运行grep -r ', \*\*' .并发现是的,stdlib 中有使用的方法**kwargs,但仅在open3.rb库中。

./lib/ruby/2.1.0/open3.rb:  def popen3(*cmd, **opts, &block)
./lib/ruby/2.1.0/open3.rb:  def popen2(*cmd, **opts, &block)
./lib/ruby/2.1.0/open3.rb:  def popen2e(*cmd, **opts, &block)
./lib/ruby/2.1.0/open3.rb:  def capture3(*cmd, stdin_data: '', binmode: false, **opts)
./lib/ruby/2.1.0/open3.rb:  def capture2(*cmd, stdin_data: '', binmode: false, **opts)
./lib/ruby/2.1.0/open3.rb:  def capture2e(*cmd, stdin_data: '', binmode: false, **opts)
./lib/ruby/2.1.0/open3.rb:  def pipeline_rw(*cmds, **opts, &block)
./lib/ruby/2.1.0/open3.rb:  def pipeline_r(*cmds, **opts, &block)
./lib/ruby/2.1.0/open3.rb:  def pipeline_w(*cmds, **opts, &block)
./lib/ruby/2.1.0/open3.rb:  def pipeline_start(*cmds, **opts, &block)
./lib/ruby/2.1.0/open3.rb:  def pipeline(*cmds, **opts)

编辑

在@mdesantis 的建议下,我对MRI 标识符进行了搜索rb_get_kwargs;事实证明,C 核心库中至少有一些方法使用关键字 args。

Dir.new( string, encoding: enc ) -> aDir

Array#sample(n, random: rng) -> new_ary
Array#shuffle!(random: rng) -> ary

GC.start(full_mark: false) -> nil
于 2014-02-17T10:42:04.483 回答