如何访问 Ruby splat 参数?

How to access a Ruby splat argument?

我已经覆盖了我的设计 gem 中的 send_devise_notification 方法。

我需要访问 *args 数组中的第一个元素,我认为这可以通过 *args[0] 来实现。

我期待一个字符串,但请查看下面的奇怪输出:

class User
  include Mongoid::Document

  devise :confirmable, :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :lockable

  protected

    def send_devise_notification(notification, *args)
      p *args.inspect               # => ["auNsGzsnpoQWtAk2Z1Tr", {}]
      p *args[0].inspect            # => "auNsGzsnpoQWtAk2Z1Tr"
      p *args[0].class.to_s.inspect # => "String"
      token = *args[0]
      p token.inspect               # => ["auNsGzsnpoQWtAk2Z1Tr"]
      p token.class.to_s.inspect    # => "Array"
    end
end

当我记录它时,我看到了一个字符串。但是当我将它放入 token 变量时,我看到了一个数组。而且我无法将变量转换为字符串。我试过token.to_s

知道发生了什么吗?

你应该使用 args,它是一个数组:

def a(*args)
   args.each {|e| puts "-- #{e}" }
end  

a(1,2,3,4)
#-- 1
#-- 2
#-- 3
#-- 4
#=> [1, 2, 3, 4]

因此,如果您想获取它的第一个元素 - 调用 args[0]args.first(不带前导星号)。

你可以用args.first获取第一个元素,因为*args是一个数组。