Ruby 函数将字典指针作为参数,为什么


def to_json(*opts)
  {
    'json_class'   => self.class.name,
    'data' => { 'term' => @term,
                'command' => @command,
                'client' => client
              }
  }.to_json(*opts)
end

为什么这个 Ruby 函数将字典指针*opts作为参数,而不仅仅是opts?这里有什么好处?

*opts 中的星号*不是指针(如 C/C++)。Ruby 中没有这样的指针概念。


定义方法时,它用于拼接。例如:

def foo(first, *rest)
  "first=#{first}. rest=#{rest.inspect}"
end
puts foo("1st", "2nd", "3rd")
# => first=1st. rest=["2nd", "3rd"]

调用方法时,它用于扩展参数。例如:

arr = ["2nd", "3rd"]
bar("1st", *arr)

相当于:

bar("1st", "2nd", "3rd")

最新更新