69

Railsヘルパーファイルにこのようなメソッドがあります

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

このようにこのメソッドを呼び出せるようにしたい

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

フォームのコミットに基づいて引数を動的に渡すことができるようにします。あまりにも多くの場所で使用しているため、メソッドを書き直すことができません。他にどのようにこれを行うことができますか?

4

3 に答える 3

94

Rubyは複数の引数をうまく処理します。

これはかなり良い例です。

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"]]}

(irbから切り取って貼り付けた出力)

于 2009-05-06T19:23:15.577 に答える
68

このように呼んでください:

table_for(@things, *args)

splat*演算子は、メソッドを変更せずにジョブを実行します。

于 2009-05-06T19:11:48.197 に答える
0
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
于 2015-06-18T09:30:01.340 に答える