Created
December 22, 2014 06:03
-
-
Save k2works/b29b4aa4f4ebc8abf529 to your computer and use it in GitHub Desktop.
メソッドをevalで定義する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LoggingInstanceVariable | |
logging_instance_val_names = %w(first_val second_val third_val) | |
logging_instance_val_names.each do |val_name| | |
eval <<-END_OF_DEF | |
attr_reader :#{val_name}, :before_#{val_name} | |
def #{val_name}=(val) | |
@before_#{val_name} = @#{val_name} | |
@#{val_name} = val | |
end | |
END_OF_DEF | |
end | |
end | |
obj = LoggingInstanceVariable.new | |
obj.first_val = 1 | |
obj.first_val = 2 | |
obj.first_val # => 2 | |
obj.before_first_val # => 1 | |
obj.first_val # => 2 | |
obj.before_first_val # => 1 | |
obj.third_val = :third_val | |
obj.third_val = 'third_val' | |
obj.third_val # => "third_val" | |
obj.before_third_val # => :third_val |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment