2017-08-16 30 views
2

所以我一直在Traiblazer和改革文件,我經常看到這樣的代碼這個代碼示例中的double splat(**)參數是什麼意思,爲什麼使用它?

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:, **)定義是什麼?

我很清楚雙啪啪命名參數(如**others)捕獲所有其他關鍵字參數。但我從來沒有見過**,沒有名字。

所以我的2個問題是:

  1. 什麼**在上面的塊是什麼意思?
  2. 爲什麼使用這種語法?

回答

7

**在上面的代碼段中表示的是什麼?

這是一個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" 
+2

同樣的模式也適用於常規參數。單個splat參數將接受任何參數,但不會將它們分配給變量。 –

+1

@HolgerJust:是的,當然,謝謝你的提及。 –