Created
November 27, 2010 20:40
-
-
Save igrigorik/718252 to your computer and use it in GitHub Desktop.
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
module Selectable | |
def recieve?; false; end | |
def send?; true; end | |
end | |
class Channel | |
include Selectable | |
def recieve | |
'hai' | |
end | |
end | |
class Selector | |
def initialize | |
@cases = [] | |
@immediate = nil | |
@default = nil | |
end | |
def default(&blk); @default = blk; end | |
def case(condition, &blk) | |
@immediate = blk if condition && !@immediate | |
@cases.push blk | |
end | |
def select | |
if @immediate | |
@immediate.call | |
elsif [email protected]? | |
@default.call | |
else | |
p [@cases.size, :cases] | |
end | |
end | |
end | |
def select(&blk) | |
s = Selector.new | |
yield s | |
s.select | |
end | |
c = Channel.new | |
select do |s| | |
s.case(c.recieve?) { p c.recieve } | |
s.case(false) { p 2 } | |
s.default { p :default } | |
end | |
select do |s| | |
s.case(c.recieve?) { p c.recieve } | |
s.case(true) { p true } | |
end | |
select do |s| | |
s.case(false) { p false } | |
end | |
puts "Done" | |
# :default | |
# true | |
# [1, :cases] | |
# Done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment