方法的动态参数

时间:2015-05-08 21:06:09

标签: ruby metaprogramming dynamic-programming

对于我想从动态上下文调用的类,我有一些常规的set方法。但是我在从变量构建方法调用时遇到了麻烦。

示例代码设置器

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

我知道为什么工作调用工作,/'/ inside('dd')。但由于它可能是一个数字,即set_size(55),我不能总是在这个值附近。 那么我怎么能构造一个调用我的get / set方法的字符串呢?我想这是“#{the_value}”“这部分不起作用,因为我希望它。

2 个答案:

答案 0 :(得分:2)

基本上你会这样做......

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

答案 1 :(得分:1)

你有没有尝试过:

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