【问题标题】:Passing an array's elements as arguments to a method将数组的元素作为参数传递给方法
【发布时间】:2013-07-11 02:08:21
【问题描述】:
class Test
  def initialize(*args)
    print "I got #{args.length} arguments!"
  end
end

arguments = ["Hello",100,30]

Test.new(arguments)

在那里,Test 只接收一个参数(一个数组)。是否可以将数组的元素作为Test 的参数传递?这样Test 的构造函数就标识了三个参数。

【问题讨论】:

    标签: ruby methods arguments


    【解决方案1】:

    您想使用splat operator、*。

    class Test
      def initialize(*args)
        print "I got #{args.length} arguments!"
      end
    end
    
    arguments = ["Hello",100,30]
    
    Test.new(*arguments)
    

    【讨论】:

      【解决方案2】:

      喷他们:Test.new(*arguments)

      【讨论】:

        猜你喜欢
        • 2020-03-16
        • 2012-05-24
        • 2016-11-18
        • 2013-01-24
        • 1970-01-01
        • 1970-01-01
        • 2018-12-11
        • 2015-02-12
        • 2017-10-01
        相关资源
        最近更新 更多