jemnotesversion 2 / featuring this entry or see all/search

May 18
This little fragment extends the ruby string class to check that all round, square and curly brackets occur in appropriate couplings.
class String
  def brackets_match?
    stack = []
    each_char do |c|
      case c
      when '(', '[', '{'
        stack << c
      when ')'
        return false unless stack.pop == '('
      when '}'
        return false unless stack.pop == '{'
      when ']'
        return false unless stack.pop == '['
      end
    end
    stack.empty?
  end
end
and the tests:
should 'test matching brackets' do
  assert '(this)'.brackets_match?
  assert '(this)(fine)'.brackets_match?
  assert '(this)(fine)'.brackets_match?
  assert '[this][fine]'.brackets_match?
  assert '(this){fine}'.brackets_match?
  assert '(thi(s)){fine}'.brackets_match?

  refute '(thi(s)((fine)'.brackets_match?
  refute '{this){fine}'.brackets_match?
  refute '{this)(fine}'.brackets_match?
  refute '{this)(fine}'.brackets_match?
end