2011-06-23 59 views
0

我想要使用繼承的格式方法來格式化十六進制字符串。我有點像Ruby-noob,任何幫助表示讚賞。Ruby:繼承的動態設置器

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 

回答

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 
+0

我想,我的'attribute.owner'在send'的'前指的是Foo類,而不是富實例。謝謝你,先生。你是個學者和紳士。 – roris