方法的动态参数

Dynamic parameters for method

我有一些 class 的常规设置方法,我想从动态上下文中调用这些方法。但是我在从变量建立方法调用时遇到了麻烦。

示例代码 setters

def set_name(value)
  @name = value
end
def set_size(value)
  @size = value
end

现在我想从另一个方法调用这些 setter。例如

def call_setter(variable, method_name)
      #vaiable could be FixedNr/String/boolean etc
      #method_name is a string which = 'name' or 'size' or ...
  set_name("Mike") # this works, however i
      # need to do it dynamically from the par, since it
      # could be set_name, set_size etc. I have tried:

      #This should create the correct look of the method
  method_call = 'set_'+method_name + '(' + "#{the_value}" + ')'

  send(method_call) #Gives error undefined method `set_name(Mike)' for MyClass
  eval(method_call) #No such method error
  method_call # doesn nothing

      #Another working undynamic solution
  m1 = 'set_' + 'name'
  m2 = '(' + "'" +  "Mike" + "'" + ')'
  m = m1 + m2
  eval(m) #This works.
end

我知道为什么工作调用有效,里面的 /'/ ('dd')。但是因为它可能是一个数字,即 set_size(55) 我不能总是在值周围有 '' 。 那么我如何构造一个调用我的 get/set 方法的字符串呢?我想是这部分“#{the_value}”没有像我希望的那样工作。

这基本上就是您的操作方式...

def name=(value)
  @name = value
end

def size=(value)
  @size = value
end

# or even easier since the above are just basic setters: 
# attr_accessor :name, :value

def call_setter(variable, method_name)
  self.send "#{method_name}=", variable
end

你试过了吗:

method_name = method_name.match(/^set_/) ? "#{method_name}=" : "set_#{method_name}="
send method_name, variable