ruby-on-railsarraysrubydevisesplat

How to access a Ruby splat argument?


I have overridden the send_devise_notification methods from my devise gem.

I need to access the first element in the *args array, and I would assume this can be achieved with *args[0].

I am expecting a string, but check out the strange output below:

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

When I log it, I see a string. But when I put it into a token variable I see an array. And I can't convert the variable into a string. I have tried token.to_s, etc.

Any idea what's happening?


Solution

  • You should use args and it's an array:

    def a(*args)
       args.each {|e| puts "-- #{e}" }
    end  
    
    a(1,2,3,4)
    #-- 1
    #-- 2
    #-- 3
    #-- 4
    #=> [1, 2, 3, 4]
    

    So if you want to get its first element - call args[0] or args.first (without the leading asterisk).