我正在尝试使用继承格式方法格式化十六进制字符串。我有点像Ruby-noob,感谢任何帮助。
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
答案 0 :(得分:1)
这是一种做你想做的事情的方法:
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