点击(此处)折叠或打开
- class Module
- def var( method_name )
- inst_variable_name = "@#{method_name}".to_sym
- # .to_sym
- p inst_variable_name #:=>:@bar
- define_method method_name do
- instance_variable_get inst_variable_name
- end
- define_method "#{method_name}=" do |new_value|
- instance_variable_set inst_variable_name, new_value
- end
- end
- end
- class Foo
- var :bar
- end
- f = Foo.new
- # p f.bar
- p f.class #:=>Foo
- p f.class.instance_methods(false) #:=>["bar", "bar="]
- f.bar = "good" #:=>"good" method bar=
- p f.bar #:=>"good" method bar
点击(此处)折叠或打开
- class Fred
- def initialize(p1, p2)
- @a, @b = p1, p2
- end
- end
- fred = Fred.new('cat', 99)
- fred.instance_variable_get(:@a) #=> "cat"
- fred.instance_variable_get("@b") #=> 99
我们都知道在ruby中:a等价于"a"但用前面的方法会更清爽,并且少写一个符号。