Last active
June 20, 2023 03:31
-
-
Save dchapman1988/970670a5ce9eb7f89ac15cc70ddc7a84 to your computer and use it in GitHub Desktop.
Fun with blocks, procs and lambdas.
This file contains hidden or 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 Adventurer | |
attr_accessor :name, :location | |
def initialize(name, location = "Edge of Forest") | |
@name = name | |
@location = location | |
end | |
def move(&block) | |
block.call(self) | |
end | |
end | |
class Forest | |
attr_accessor :areas | |
def initialize | |
@areas = { | |
"Edge of Forest" => Proc.new do |adventurer, callback| | |
puts "#{adventurer.name} is standing at the edge of the forest." | |
callback.call("birds singing") if callback | |
end, | |
"Deep in Forest" => Proc.new do |adventurer, callback| | |
puts "#{adventurer.name} is lost deep within the forest." | |
callback.call("a rustling in the bushes") if callback | |
end, | |
"Forest Clearing" => Proc.new do |adventurer, callback| | |
puts "#{adventurer.name} found a clearing with a serene pond." | |
callback.call("a fish jumping in the pond") if callback | |
end | |
} | |
end | |
def explore(area, adventurer, &callback) | |
if @areas.key?(area) | |
@areas[area].call(adventurer, callback) | |
else | |
lambda { |adventurer| puts "#{adventurer.name} wandered into an unknown part of the forest." }.call(adventurer) | |
end | |
end | |
end | |
def observe(event) | |
puts "While exploring, you observe: #{event}" | |
end | |
forest = Forest.new | |
bob = Adventurer.new("Bob") | |
bob.move do |adventurer| | |
adventurer.location = "Deep in Forest" | |
end | |
forest.explore(bob.location, bob) do |event| | |
observe(event) | |
end | |
bob.move do |adventurer| | |
adventurer.location = "Forest Clearing" | |
end | |
forest.explore(bob.location, bob) do |event| | |
observe(event) | |
end | |
bob.move do |adventurer| | |
adventurer.location = "Dark Cave" | |
end | |
forest.explore(bob.location, bob) do |event| | |
observe(event) | |
end |
This file contains hidden or 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
Bob is lost deep within the forest. | |
While exploring, you observe: a rustling in the bushes | |
Bob found a clearing with a serene pond. | |
While exploring, you observe: a fish jumping in the pond | |
Bob wandered into an unknown part of the forest. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment