Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Berkeley SaaS class HW1 Part 5: advanced OOP with some metaprogramming
# advanced OOP with some metaprogramming
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s
# getter
attr_reader attr_name
attr_reader attr_name+"_history"
# 为类动态添加方法
class_eval %{
def #{attr_name}=(val)
@#{attr_name} = val
@#{attr_name}_history = [nil] if @#{attr_name}_history.nil?
@#{attr_name}_history.push(val)
end
}
end
end
class Foo
attr_accessor_with_history :bar
end
f = Foo.new
f.bar = 1
f.bar = 2
p f.bar
p f.bar_history # => if your code works, should be [nil,1,2]
@yamishi13

thanks for showing me the correct way to do it but could you tell me where did you learn to do it? on the book of the course?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.