如何将多个参数作为数组传递给 ruby​​ 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/831077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:13:21  来源:igfitidea点击:

How do I pass multiple arguments to a ruby method as an array?

ruby-on-railsrubyarraysmethodsarguments

提问by Chris Drappier

I have a method in a rails helper file like this

我在这样的 rails helper 文件中有一个方法

def table_for(collection, *args)
 options = args.extract_options!
 ...
end

and I want to be able to call this method like this

我希望能够像这样调用这个方法

args = [:name, :description, :start_date, :end_date]
table_for(@things, args)

so that I can dynamically pass in the arguments based on a form commit. I can't rewrite the method, because I use it in too many places, how else can I do this?

这样我就可以根据表单提交动态传递参数。我无法重写该方法,因为我在太多地方使用它,我还能怎么做?

回答by sean lynch

Ruby handles multiple arguments well.

Ruby 可以很好地处理多个参数。

Here isa pretty good example.

这是一个很好的例子。

def table_for(collection, *args)
  p collection: collection, args: args
end

table_for("one")
#=> {:collection=>"one", :args=>[]}

table_for("one", "two")
#=> {:collection=>"one", :args=>["two"]}

table_for "one", "two", "three"
#=> {:collection=>"one", :args=>["two", "three"]}

table_for("one", "two", "three")
#=> {:collection=>"one", :args=>["two", "three"]}

table_for("one", ["two", "three"])
#=> {:collection=>"one", :args=>[["two", "three"]]}

(Output cut and pasted from irb)

(从 irb 剪切和粘贴的输出)

回答by Maximiliano Guzman

Just call it this way:

就这样称呼它:

table_for(@things, *args)

The splat(*) operator will do the job, without having to modify the method.

splat*)运算符将做的工作,而不必修改的方法。

回答by Anoob K Bava

class Hello
  $i=0
  def read(*test)
    $tmp=test.length
    $tmp=$tmp-1
    while($i<=$tmp)
      puts "welcome #{test[$i]}"
      $i=$i+1
    end
  end
end

p Hello.new.read('johny','vasu','shukkoor')
# => welcome johny
# => welcome vasu
# => welcome shukkoor