双splat(**)参数在这个代码示例中意味着什么以及为什么要使用它?

Dor*_*ian 3 ruby ruby-on-rails reform trailblazer

所以我一直在使用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
Run Code Online (Sandbox Code Playgroud)

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

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

所以我的两个问题是:

  1. 在上面的块中**意味着什么?
  2. 为什么要用这个语法?

Ser*_*sev 9

**在上面的块中意味着什么?

这是一个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"
Run Code Online (Sandbox Code Playgroud)

  • 相同的模式也适用于常规参数.单个splat参数将接受任何参数,但不会将它们分配给变量. (2认同)