Ruby: Dynamic setter with inheritance
I'm tr开发者_Go百科ying to format hex strings using an inherited format method. I'm a bit of a Ruby-noob, any help is appreciated.
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
Here's one way to do what you wanted to do:
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
精彩评论