Created
December 20, 2018 12:12
-
-
Save zmalltalker/3225ff7b83c5efc60c8cd20248bf6621 to your computer and use it in GitHub Desktop.
Callbacks, Ruby-style
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
q1 = Question.new("What is the color of my eyes?", "blue") | |
q1.ask do |answer| | |
answer.correct { puts "Nice!" } | |
answer.incorrect { puts "LOL" } | |
end |
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 Question | |
def initialize(question, correct_answer) | |
@question = question | |
@correct_answer = correct_answer | |
end | |
def ask | |
puts @question | |
answer = gets.chomp | |
if correct?(answer) | |
yield CorrectAnswer.new | |
else | |
yield IncorrectAnswer.new | |
end | |
end | |
def correct?(answer) | |
answer == @correct_answer | |
end | |
end | |
class Answer | |
def correct | |
end | |
def incorrect | |
end | |
end | |
class CorrectAnswer < Answer | |
def correct | |
yield | |
end | |
end | |
class IncorrectAnswer < Answer | |
def incorrect | |
yield | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment