*运算符在属性数组之前做什么?

时间:2019-02-11 15:40:21

标签: ruby

我在阅读的文章中看到了这一行代码,无法弄清楚*是什么。

module Presenter
  class Person
    attr_reader :json

    PERSON_ATTRS  = [:person, :attributes]
    COUNTRY_NAME  = PERSON_ATTRS + [:address, :country, :name]
    STREET_NAME   = PERSON_ATTRS + [:address, :street]

    def initialize(person_json)
      @json = person_json
    end

    def country
      json.dig(*COUNTRY_NAME)
    end

    def street
      json.dig(*STREET_NAME)
    end
  end
end

它位于属性数组之前,当我运行不带*的代码时,dig返回nil。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

数组前面的*运算符称为splat运算符。

dig方法签名带有多个参数。如果要将数组转换为参数列表,则splat运算符将执行以下操作:https://medium.freecodecamp.org/rubys-splat-and-double-splat-operators-ceb753329a78

它返回nil的原因是因为dig将查找键[:person, :attributes]

json = {person: {attributes: "something"} }
json.dig(*PERSON_ATTRS) # something
json = {[:person :attributes] => "something"} }
json.dig(PERSON_ATTRS) # something