Skip to content

Instantly share code, notes, and snippets.

@bayleedev
Last active August 29, 2015 13:56
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 bayleedev/9079590 to your computer and use it in GitHub Desktop.
Save bayleedev/9079590 to your computer and use it in GitHub Desktop.
Give it a tree (array) and it will evaluate them in a short-circuit evaluation fashion.
# Helps with executing, and short-circut evaluation.
class ShortCircuitIterator
def initialize(tree)
@tree = tree
end
# Executes all the OR logic breaking on the first `true`-ish value
def each(&block)
@tree.each do |and_operation|
break if and_block(and_operation, &block)
end
end
protected
# Executes all the && logic breaking on the first `false`-ish value
def and_block(and_operation, &block)
and_operation.inject(true) do |memo, commands|
break(false) unless execute_commands(commands, &block)
true
end
end
# Executes commands or series of commands (separated by semicolons)
def execute_commands(commands, &block)
Array([commands]).flatten.inject(true) do |memo, command|
block.call(command)
end
end
end

The first level is OR

one || two #=> [one, two]

The second level is &&

one && two #=> [[one, two]]
one && two || three #=> [[one, two], three]

Third level is MEH (semicolon)

one && two || three; four => [[one, two], [[three, four]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment