在此代码示例中,双 splat (**) 参数是什么意思,为什么要使用它?



所以我看过Traiblazer和Reform文档,我经常看到这种代码

class AlbumForm < Reform::Form
collection :songs, populate_if_empty: :populate_songs! do
property :name
end
def populate_songs!(fragment:, **)
Song.find_by(name: fragment["name"]) or Song.new
end
end

注意到def populate_songs!(fragment:, **)定义了吗?

我很清楚捕获所有其他关键字参数的双 splat 命名参数(如**others(。但我从未见过**一个人,没有名字。

所以我的两个问题是:

  1. 上面的块中的**是什么意思?
  2. 为什么要使用此语法?
上面的

块中**是什么意思?

这是一个 kwsplat,但没有分配名称。因此,此方法将接受任意一组关键字参数并忽略除:fragment之外的所有参数。

为什么要使用此语法?

忽略你不感兴趣的论点。


一个小演示

class Person
attr_reader :name, :age
def initialize(name:, age:)
@name = name
@age = age
end
def description
"name: #{name}, age: #{age}"
end
end
class Rapper < Person
def initialize(name:, **)
name = "Lil #{name}" # amend one argument
super # send name and the rest (however many there are) to super
end
end
Person.new(name: 'John', age: 25).description # => "name: John, age: 25"
Rapper.new(name: 'John', age: 25).description # => "name: Lil John, age: 25"

最新更新