Skip to content

Instantly share code, notes, and snippets.

@eipipuz
Created December 26, 2008 03:19
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 eipipuz/39998 to your computer and use it in GitHub Desktop.
Save eipipuz/39998 to your computer and use it in GitHub Desktop.
I made this file to scratch an itch. I'm learning Python and I found they have "new" control flows. They have a while/else. This made me go to Wikipedia and see if there were any others I was ignoring. This in turn made me come to exit_when. It's like a Case statement with a While mixed in.
Will I ever use it? Dunno. Have I found any useful scenario? Not yet.
(I'm sure a better Rubyist can make a better implementation. If someone knows a better way, please let me know.)
Enjoy.
def infinite_loop
yield while(true)
end
def exit_when(options)
found = false
result = nil
result_yield = nil
infinite_loop {
result_yield = yield
if (options.keys.include? result_yield) ||
(options.keys.include? result_yield.class and
result_yield = result_yield.class)
result = options[result_yield]
break
end
}
if result.is_a? Proc
result.call(result_yield)
else
result
end
end
def while_else(clauses)
called_once = false
while (clauses[:condition].call) do
called_once = true
clauses[:body].call
end
clauses[:else].call unless called_once
end
if __FILE__ == $0
rslt = exit_when(
1 => 'one',
Symbol => proc {|x| puts x},
'12' => String
) {
number = (rand * 15).floor
puts number
('12' if number == 12) or
(:even if number % 2 == 0) or
number
}
puts rslt unless rslt.nil?
def buy_upgrades(credits_available)
while_else({ :condition => proc {credits_available > 0},
:body => proc{credits_available -= (rand * 3).floor
puts "#{credits_available} left"},
:else => proc{puts "No upgrade possible."}
})
end
puts "----------------"
buy_upgrades(10)
puts "----------------"
buy_upgrades(0)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment