【问题标题】:How do I pass multiple arguments to a ruby method as an array?如何将多个参数作为数组传递给 ruby​​ 方法?
【发布时间】:2010-10-24 06:48:21
【问题描述】:

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

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

我希望能够像这样调用这个方法

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

这样我就可以根据表单提交动态传递参数。无法重写方法,因为我用的地方太多了,不然怎么办?

【问题讨论】:

    标签: ruby-on-rails ruby arrays methods arguments


    【解决方案1】:

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

    Here is 一个很好的例子。

    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 剪切和粘贴的输出)

    【讨论】:

    【解决方案2】:

    就这样称呼吧:

    table_for(@things, *args)
    

    splat (*) 运算符将完成这项工作,而无需修改方法。

    【讨论】:

    • 这正是我想要的。
    • 我试图从一个数组中为一个固定的方法组合参数,你的回答帮助感谢例如; method(*['a', '', nil].compact_blank)
    【解决方案3】:
    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
    

    【讨论】:

    • 你能不能再补充一个解释?
    • 首先,创建一个指针test,它就像一个数组,然后,找到数组长度。然后我们必须迭代循环直到计数器达到长度。然后在循环中它将打印带有方法中所有争论的欢迎消息
    • i 在这里定义为全局变量。当类被加载时,它只会被设置为零一次。所以read 函数的第二次运行将永远无法工作。
    猜你喜欢
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2011-02-12
    • 2021-07-19
    • 1970-01-01
    • 2015-12-21
    • 2011-03-17
    • 2013-11-21
    相关资源
    最近更新 更多