Ruby:带继承的动态setter

Ruby:带继承的动态setter,ruby,inheritance,dynamic,Ruby,Inheritance,Dynamic,我正在尝试使用继承的格式化方法格式化十六进制字符串。我是一个有点鲁比的笨蛋,任何帮助都是感激的 class Bar def alter_the_variable attribute_name attribute = method(attribute_name) formatted = "%.4x" % attribute.call.hex puts formatted # => 00f3 attribute = formatted # What

我正在尝试使用继承的格式化方法格式化十六进制字符串。我是一个有点鲁比的笨蛋,任何帮助都是感激的

class Bar
  def alter_the_variable attribute_name
    attribute = method(attribute_name)
    formatted = "%.4x" % attribute.call.hex
    puts formatted    # => 00f3
    attribute = formatted   # What I "want" to be able to do, but
                            # doesn't work because attribute is a local variable

    #attribute.owner.send(:h=, formatted)   # Doesn't work either, gives:
                                            # in `send': undefined method `h=' for Foo:Class (NoMethodError)
  end
end

class Foo < Bar
  def initialize
    @h = "f3"
  end

  def h
    @h
  end

  def h= val
    @h = val
  end
end

f = Foo.new
puts f.h    # => f3
f.alter_the_variable :h
puts f.h    # => f3
类栏
def alter__变量属性_名称
属性=方法(属性\名称)
格式化=“%.4x”%attribute.call.hex
将格式化的#=>00f3
attribute=格式化#我“想要”做什么,但是
#无法工作,因为属性是局部变量
#attribute.owner.send(:h=,格式化)#也不起作用,给出:
#在'send'中:Foo:Class(NoMethodError)的未定义方法'h='
结束
结束
等级Foof3
f、 改变变量:h
将f.h#=>f3

这里有一种方法可以做你想做的事情:

def alter_the_variable attribute_name
  current_value = send(attribute_name)
  formatted_value = "%.4x" % current_value.hex
  send (attribute_name.to_s+'=').to_sym, formatted_value
end

我猜
send
前面的
attribute.owner
指的是Foo类,而不是Foo实例。谢谢你,先生。你是一位学者和绅士。