Skip to content

Instantly share code, notes, and snippets.

@rachelmyers
Created February 14, 2011 07:19
Show Gist options
  • Save rachelmyers/825584 to your computer and use it in GitHub Desktop.
Save rachelmyers/825584 to your computer and use it in GitHub Desktop.
My first state machine! Hooray!
STATE_CHOPPING_FRONT = 0
#STATE_ITERATING_END = 1
STATE_CHOPPING_END = 2
STATE_FINISHED = 3
def strip(array)
state = STATE_CHOPPING_FRONT
loop do
if state == STATE_CHOPPING_FRONT then
if array[0].white_space?
array.delete_at(0) # array.shift
else
state = STATE_CHOPPING_END
end
elsif state == STATE_CHOPPING_END then
if array.last.white_space?
array.delete_at(array.length - 1) # array.pop
else
state = STATE_FINISHED
end
elsif state == STATE_FINISHED
break
end
end
array
end
class String
def white_space?
self == " " || self == "\t" || self == "\r" || self == "\n"
end
end
p strip(" foo ".split(''))
p strip(" foo b".split(''))
p strip("b foo ".split(''))
p strip("foo".split(''))
p strip("f oo".split(''))
p strip("\tfoo \n".split(''))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment