Question

J'ai une méthode dans un fichier d'aide aux rails comme celui-ci

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

et je veux pouvoir appeler cette méthode comme ceci

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

afin que je puisse passer dynamiquement les arguments basés sur une validation de formulaire. Je ne peux pas réécrire la méthode, car je l'utilise dans trop d'endroits. Sinon, comment puis-je faire cela?

Était-ce utile?

La solution

Ruby gère bien plusieurs arguments.

Voici un très bon exemple.

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

(sortie coupée et collée depuis irb)

Autres conseils

Appelez-le simplement de cette façon:

table_for(@things, *args)

L'opérateur splat ( * ) fera le travail, sans avoir à modifier la méthode.

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top