Created
May 25, 2013 14:39
-
-
Save mryoshio/5649292 to your computer and use it in GitHub Desktop.
Method practice.
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
# dynamic dispatch | |
puts '##### dynamic dispatch' | |
class Student | |
def initialize | |
@name = 'Joe' | |
end | |
def original | |
"#{@name}'s original score: { math: 60, eng: 56 }" | |
end | |
end | |
s = Student.new | |
puts s.send(:original) #=> { :math=>60, :eng=>56 } | |
# dynamically define method | |
puts '##### dynamically define method' | |
class Student | |
define_method :cheating do | |
"#{@name}'s cheating score: { math: 98, eng: 96 }" | |
end | |
end | |
puts s.cheating #=> { :math=>98, :eng=>96 } | |
# ghost method | |
puts '##### ghost method' | |
class Student | |
def method_missing(method_name) | |
if method_name =~ /^report$/ | |
"#{method_name}: not want to study!" | |
else | |
super | |
end | |
end | |
end | |
puts s.report | |
begin | |
puts s.report_not_exists | |
rescue Exception => ex | |
puts ex | |
end | |
# dynamic proxy | |
puts '##### dynamic proxy' | |
class Student | |
def method_missing(method_name) | |
if method_name =~ /^study_hard$/ | |
cheating | |
else | |
super | |
end | |
end | |
end | |
puts s.study_hard |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment