【问题标题】:Rails - variable as part of method name [duplicate]Rails - 作为方法名称一部分的变量[重复]
【发布时间】:2011-12-03 09:06:21
【问题描述】:

可能重复:
Calling a Function From a String With the Function's Name in Ruby

我想做这样的事情:

  def self.greater_than(col_str='events')
    self."#{col_str}"_greater_than(30) # search logic scope method
  end

我怎样才能让它正确调用?我猜语法可能类似于创建动态方法。

【问题讨论】:

    标签: ruby-on-rails ruby variables dynamic methods


    【解决方案1】:

    你可以试试send

    send("#{col_str}_greater_than".to_sym, 30)
    

    【讨论】:

      【解决方案2】:

      试试这个

      def self.greater_than(col_str='events')
        self.send("#{col_str}_greater_than", 30) # search logic scope method
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-23
        • 2014-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        相关资源
        最近更新 更多