Jak przekazać wiele argumentów do metody ruby jako tablicę?

Mam metodę w pliku helpera rails jak Ta

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

I chcę być w stanie wywołać tę metodę w ten sposób

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

Abym mógł dynamicznie przekazywać argumenty na podstawie commita formularza. Nie mogę przepisać metody, ponieważ używam jej w zbyt wielu miejscach, jak inaczej mogę to zrobić?

Author: Bill the Lizard, 2009-05-06

3 answers

Ruby dobrze obsługuje wiele argumentów.

Oto całkiem dobry przykład.

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

(Wyjście wycięte i wklejone z irb)

 83
Author: sean lynch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-14 08:35:25

Nazwij to tak:

table_for(@things, *args)

The splat (*) operator wykona zadanie bez konieczności modyfikowania metody.

 54
Author: Maximiliano Guzman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-20 18:54:01
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
 -2
Author: Anoob K Bava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-20 18:55:16