سؤال

ولدي أسلوب في ملف القضبان المساعد مثل هذا

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

ووأريد أن أكون قادرة على استدعاء هذا الأسلوب مثل هذا

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

وحتى أستطيع أن يمر حيوي في الحجج القائمة على نموذج الالتزام. لا أستطيع كتابة الطريقة، لأنني استخدامها في العديد من الأماكن، وإلا كيف يمكن أن أفعل هذا؟

هل كانت مفيدة؟

المحلول

روبي يتعامل مع الحجج متعددة أيضا.

<وأ href = "https://web.archive.org/web/20170113103604/http://www.misuse.org/science/2008/01/30/passing-multiple-arguments-in-ruby- هو الخاص بك بين صديق "يختلط =" noreferrer "> هنا مثال جيد جدا.

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)

نصائح أخرى

وفقط اتصل على هذا النحو:

table_for(@things, *args)

وو(splat) مشغل * سوف قيام بهذه المهمة، دون الحاجة إلى تعديل أسلوب.

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top