Ruby/String/String class Extension
Материал из Wiki.crossplatform.ru
Add method to system type
class String def substitute(binding=TOPLEVEL_BINDING) eval(%{"#{self}"}, binding) end end template = %q{static string #{food}!} food = "b" template.substitute(binding) food = "p" template.substitute(binding)
Adds last character of provided string to front of self
class String def pop return nil if self.empty? item=self[-1] self.chop! return nil if item.nil? item.chr end def unshift(other) newself = other.to_s.dup.pop.to_s + self self.replace(newself) end end a = "this is a test" puts (a.unshift "asfd")
Adds provided string to front of self
class String def unshift_word(other) newself = other.to_s + self self.replace(newself) end end a = "this is a test" puts a.unshift_word "another"
convert string to binary number
class String def bin val = self.strip pattern = /^([+-]?)(0b)?([01]+)(.*)$/ parts = pattern.match(val) return 0 if not parts sign = parts[1] num = parts[3] eval(sign+"0b"+num) end end a = "10011001".bin b = "0b10011001".bin c = "0B1001001".bin d = "nothing".bin e = "0b100121001".bin
Get acronym
class String def acronym(thresh=0) acro="" str=self.dup.strip while !str.nil? && !str.empty? word = str.shift_word if word.length >= thresh acro += word.strip[0,1].to_s.upcase end end acro end @@first_word_re = /^(\w+\W*)/ def shift_word return nil if self.empty? self=~@@first_word_re newself= $" || "" # $" is POSTMATCH self.replace(newself) unless $".nil? $1 end end s1 = "this is a test" puts s1.acronym
Override the method from String Class
class String def scramble (split //).sort_by { rand }.join end end class UnpredictableString < String def scramble (split //).sort_by { rand }.join end def inspect scramble.inspect end end str = UnpredictableString.new("this is a test.") puts str
Pops and returns last word off self; changes self
class String @@last_word_re = /(\w+\W*)$/ def pop_word return nil if self.empty? self=~@@last_word_re newself= $" || "" # $" is PREMATCH self.replace(newself) unless $".nil? $1 end end a = "this is a test" puts a.pop_word "another"
Pops last character off self and returns it, changing self
class String def pop return nil if self.empty? item=self[-1] self.chop! return nil if item.nil? item.chr end end a = "this is a test" puts a.pop
Processing a String One Word at a Time by adding a method to string class
class String def word_count frequencies = Hash.new(0) downcase.scan(/\w+/) { |word| frequencies[word] += 1 } return frequencies end end %{Dogs dogs dog dog dogs.}.word_count
Pushes first character of provided string onto end of self
class String def push(other) newself = self + other.to_s.dup.shift.to_s self.replace(newself) end def shift return nil if self.empty? item=self[0] self.sub!(/^./,"") return nil if item.nil? item.chr end end a = "this is a test" puts (a.push "another")
Pushes provided string onto end of self
class String def push_word(other) newself = self + other.to_s self.replace(newself) end end a = "this is a test" puts a.push_word "another"
Regular expression based comparison
class String alias old_compare <=> def <=>(other) a = self.dup b = other.dup # Remove punctuation a.gsub!(/\,\.\?\!\:\;/, "") b.gsub!(/\,\.\?\!\:\;/, "") # Remove initial articles a.gsub!(/(a |an |the )/i, "") b.gsub!(/(a |an |the )/i, "") # Remove leading/trailing whitespace a.strip! b.strip! # Use the old <=> a.old_compare(b) end end title1 = "Calling All Cars" title2 = "The Call of the Wild" # Ordinarily this would print "yes" if title1 < title2 puts "yes" else puts "no" # But now it prints "no" end
Removes first character from self and returns it, changing self
class String def shift return nil if self.empty? item=self[0] self.sub!(/^./,"") return nil if item.nil? item.chr end end a = "this is a test" puts a.shift
Replacing Multiple Patterns in a Single Pass
class String def mgsub(key_value_pairs=[].freeze) regexp_fragments = key_value_pairs.collect { |k,v| k } gsub(Regexp.union(*regexp_fragments)) do |match| key_value_pairs.detect{|k,v| k =~ match}[1] end end end "GO HOME!".mgsub([[/.*GO/i, "Home"], [/home/i, "is where the heart is"]]) # => "Home is where the heart is!" "Here is number #123".mgsub([[/[a-z]/i, "#"], [/#/, "P"]]) # => "#### ## ###### P123" "between".mgsub([[/ee/, "AA"], [/e/, "E"]]) # Good code # => "bEtwAAn"
Rotate left
class String def rotate_left(n=1) n=1 unless n.kind_of? Integer n.times do char = self.shift self.push(char) end self end def push(other) newself = self + other.to_s.dup.shift.to_s self.replace(newself) end def shift return nil if self.empty? item=self[0] self.sub!(/^./,"") return nil if item.nil? item.chr end end a = "this is a test" puts a.rotate_left
Rotate right
class String def rotate_right(n=1) n=1 unless n.kind_of? Integer n.times do char = self.pop self.unshift(char) end self end def pop return nil if self.empty? item=self[-1] self.chop! return nil if item.nil? item.chr end def unshift(other) newself = other.to_s.dup.pop.to_s + self self.replace(newself) end end a = "this is a test" puts a.rotate_right
Shifts first word off of self and returns; changes self
class String @@first_word_re = /^(\w+\W*)/ def shift_word return nil if self.empty? self=~@@first_word_re newself= $" || "" # $" is POSTMATCH self.replace(newself) unless $".nil? $1 end end a = "this is a test" puts a.shift_word
String translation
class String def rot13 self.tr("A-Ma-mN-Zn-z","N-Zn-zA-Ma-m") end end joke = "Y2K bug" joke13 = joke.rot13 # "L2X oht"
write an extension to the String class to provide it
class String def vowels self.scan(/[aeiou]/i) end end puts "This is a test".vowels.join("-")
Writing an Inherited Class
class String def scramble (split //).sort_by { rand }.join end end puts "I once was a normal string.".scramble