Skip to content

Instantly share code, notes, and snippets.

@mryoshio
Created May 25, 2013 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mryoshio/5649292 to your computer and use it in GitHub Desktop.
Save mryoshio/5649292 to your computer and use it in GitHub Desktop.
Method practice.
# 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