【问题标题】:What does double splat (**) argument mean in this code example and why use it?在此代码示例中,double splat (**) 参数是什么意思,为什么要使用它?
【发布时间】:2017-08-16 08:52:26
【问题描述】:

所以我一直在阅读 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. 为什么要使用这种语法?

【问题讨论】:

    标签: ruby-on-rails ruby reform trailblazer


    【解决方案1】:

    上面方框中的** 是什么意思?

    这是一个 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"
    

    【讨论】:

    • 同样的模式也适用于常规参数。单个 splat 参数将接受任何参数,但不会将它们分配给变量。
    • 您有此信息的来源吗?谢了!
    • @RaphaelMonteiro:我很确定它在 ruby​​ 发行说明中有简要描述(或描述链接到)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多