module StringHelpers

Public Class Methods

equalize(stringA, stringB) click to toggle source
# File lib/string_helpers.rb, line 3
def self.equalize stringA, stringB

        step1 = equalize_interpunction( stringA, stringB )
        step2 = equalize_surrounding_space( step1, stringB )
        step3 = equalize_capitalization( step2, stringB )
end

Private Class Methods

corresponding_index( strings, mark, start_index ) click to toggle source

Return index of string in list that contains given mark. Starting search at start_index. Return nil if search fails.

# File lib/string_helpers.rb, line 70
def self.corresponding_index( strings, mark, start_index )

        regexp = /#{Regexp.quote( mark )}/

        tail = strings[ start_index .. -1 ]

        return nil if tail == nil

        tail_index = tail.index { |item| item.match( regexp ) }

        return nil if tail_index == nil

        start_index + tail_index
end
equalize_capitalization(stringA, stringB) click to toggle source
# File lib/string_helpers.rb, line 12
def self.equalize_capitalization stringA, stringB

        if stringB.match( /^\s*[A-Z]/ ) and stringA.match( /^\s*[a-z]/ )

                part1 = stringA.gsub( /^(\s*)(.*)$/, '\1' )
                part2 = stringA.gsub( /^(\s*)(.*)$/, '\2' )

                return part1 + part2.capitalize
        else
                return stringA
        end
end
equalize_interpunction(stringA, stringB) click to toggle source

Return stringA with spacing around its interpunction equal to that in StringB

@example

equalize_interpunction( "A test  , succes ! ", "Comma, then exclamation!" ) => "A test, succes!"
# File lib/string_helpers.rb, line 43
def self.equalize_interpunction stringA, stringB

        punctuation_marks = "!?.,:;'@|$%^&*-+={()}\/\\\\\#\"\\\[\\\]"
        space_mark_space  = /(\s*[#{punctuation_marks}]\s*)/
        get_mark          = /\s*([#{punctuation_marks}])\s*/

        splitA = stringA.split( space_mark_space ) # "'a' ( bla )  (c    )" => ["", "'", "a", "' ", "", "( ", "bla )", "  (", "c    )"]
        splitB = stringB.split( space_mark_space )

        splitB.each_with_index do |b,indexB|

                next unless b.match( space_mark_space )

                markB = b.gsub( get_mark, '\1' );

                indexA = corresponding_index( splitA, markB, indexB )

                splitA[ indexA ] = b unless indexA == nil
        end

        splitA.join('')
end
equalize_surrounding_space(stringA, stringB) click to toggle source

Return second string, with outer surrounding spacing like first string @example

space_equally_surrounding( "gnu ", "   gnat  " ) => "   gnu  "
# File lib/string_helpers.rb, line 29
def self.equalize_surrounding_space stringA, stringB

        prefix = stringB.match( /^\s*/ )[0]
       suffix = stringB.match( /\s*$/ )[0]
        middle = stringA.gsub( /^\s*|\s*$/, '' )

        prefix + middle + suffix
end