Files
2025-09-29 00:52:08 +02:00

98 lines
2.2 KiB
Ruby
Executable File

#
# string.rb
# Additional string class methods
#
# Author:: David Muir <david.muir@rockstarnorth.com>
# Author:: Luke Openshaw <luke.openshaw@rockstarnorth.com>
# Date:: 19 February 2008
#
#-----------------------------------------------------------------------------
# Classes
#-----------------------------------------------------------------------------
class String
#
# == Description
#
# Perform multiple, simultaneous search and replace operations on a
# string.
#
# key_value_pairs is an array of RegExp => String pairs for substitution.
# String => String pairs will cause the function to generate a TypeError
# as it uses the RegExp.union method to match all occurrences in a single
# pass.
#
# == References
#
# Ruby Cookbook by Carlson and Richardson, Pg 32
#
def mgsub( key_value_pairs = [].freeze )
regexp_fragments = key_value_pairs.collect { |k, v| k }
self.gsub( Regexp.union( *regexp_fragments ) ) do |match|
key_value_pairs.detect { |k, v| k =~ match }[1]
end
end
def mgsub!( key_value_pairs = [].freeze )
regexp_fragments = key_value_pairs.collect { |k, v| k }
self.gsub!( Regexp.union( *regexp_fragments ) ) do |match|
key_value_pairs.detect { |k, v| k =~ match }[1]
end
end
#
# == Description
#
# Determines whether the string ends with the specified substring.
#
# == Example Usage
#
# 'testsendwith'.ends_with( 'with' ) => true
#
def ends_with( ends )
( self =~ /^.*#{ends}$/ ) != nil
end
#
# == Description
#
# Determines whether the string starts with the specified substring.
#
# == Example Usage
#
# 'teststartswith'.starts_with( 'tests' ) => true
#
def starts_with( start )
( self =~ /^#{start}.*$/ ) != nil
end
#
# == Description
#
# Replace all instances of target with replacement
#
# == Example Usage
#
# 'test/one/two'.replace_c('/', '') => testonetwo
#
def replace_c(target, replacement)
fmtd_bone = String.new(self)
while fmtd_bone != nil do
res = fmtd_bone
fmtd_bone = fmtd_bone.sub!(target, replacement)
end
res
end
end # String class
# End of string.rb