Skip to content

Instantly share code, notes, and snippets.

@zmalltalker
Created December 20, 2018 12:12
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 zmalltalker/3225ff7b83c5efc60c8cd20248bf6621 to your computer and use it in GitHub Desktop.
Save zmalltalker/3225ff7b83c5efc60c8cd20248bf6621 to your computer and use it in GitHub Desktop.
Callbacks, Ruby-style
q1 = Question.new("What is the color of my eyes?", "blue")
q1.ask do |answer|
answer.correct { puts "Nice!" }
answer.incorrect { puts "LOL" }
end
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