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

时间:2022-09-04 21:06:12

I have a method in a rails helper file like this

我在rails帮助文件中有这样一个方法

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?

这样我就可以动态地传递基于表单提交的参数。我不能重写这个方法,因为我在很多地方使用它,我还能怎么做呢?

3 个解决方案

#1


77  

Ruby handles multiple arguments well.

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

Here is a 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输出剪切粘贴)

#2


49  

Just call it this way:

就这么叫吧:

table_for(@things, *args)

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

splat(*)操作符将执行此任务,而不必修改方法。

#3


-2  

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

#1


77  

Ruby handles multiple arguments well.

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

Here is a 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输出剪切粘贴)

#2


49  

Just call it this way:

就这么叫吧:

table_for(@things, *args)

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

splat(*)操作符将执行此任务,而不必修改方法。

#3


-2  

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