Sha256: e53010c5f539d6eb5b45645ef9a17238b9d02ba3ed63cb3c029464ef8d440169

Contents?: true

Size: 1.21 KB

Versions: 6

Compression:

Stored size: 1.21 KB

Contents

#! /usr/bin/env ruby
# coding: utf-8

#
#
#
class String

  # Split String using correspond parentheses.
  # "(ab)(cd(ef))gh(ij)kl(mn)"  -> ["(ab)", "(cd(ef))", "gh", "(ij)", "kl", "(mn)"]
  # "((ab)(cd(ef))gh(ij)kl(mn)" -> ["((ab)(cd(ef))gh(ij)kl(mn)"]
  # "(ab)(cd(ef)))gh(ij)kl(mn)" -> ["(ab)", "(cd(ef))", ")gh(ij)kl(mn)"]
  def split_parens
    depth = 0
    current = ''
    results = []
    self.split('').each do |char|
      if char.open_paren?
        if (depth == 0 )
          results << current
          current = ''
        end
        current << char
        depth += 1
        next
      end

      if char.close_paren?
        depth -= 1
        current << char
        if (depth == 0)
          results << current
          current = ''
        end
        next
      end

      current << char
    end
    results << current
    results.delete_if{|item| item.empty? }
    return results
  end

  # Return true if self is a single character and open parenthesis.
  def open_paren?
    '({[<({[<〔【〈《「『'.split('').include?(self)
  end

  # Return true if self is a single character and close parenthesis.
  def close_paren?
    ')}]>)}]>〕】〉》」』'.split('').include?(self)
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
builtinextension-0.1.4 lib/string/splitparens.rb
builtinextension-0.1.3 lib/string/splitparens.rb
builtinextension-0.1.2 lib/string/splitparens.rb
builtinextension-0.1.1 lib/string/splitparens.rb
builtinextension-0.1.0 lib/string/splitparens.rb
builtinextension-0.0.5 lib/string_split_parens.rb