Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/string_extensions.rb

Overview

String Extensions

Author

Joel Parker Henderson, [email protected]

Copyright

Copyright (c) 2006-2008 Joel Parker Henderson

License

CreativeCommons License, Non-commercial Share Alike

License

LGPL, GNU Lesser General Public License

Ruby String base class extensions

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.prev_char(c) ⇒ Object Also known as: pred_char

Return the previous character, with a changed flag and carry flag

==Examples String.prev_char('n') => 'm', true, false # change String.prev_char('a') => 'z', true, true # change & carry String.prev_char('6') => '5', true, false # change String.prev_char('0') => '9', true, true # change & carry String.prev_char('-') => '-', false, false # unchanged



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/string_extensions.rb', line 52

def self.prev_char(c) #=> prev_char, changed_flag, carry_flag
 case c
 when '1'..'9', 'B'..'Z', 'b'..'z'
   return (c[0]-1).chr, true, false
 when '0'
   return '9', true, true
 when 'A'
   return 'Z', true, true
 when 'a'
   return 'z', true, true
 else
   return c, false, false
 end
end

Instance Method Details

#capitalize_wordsObject



22
23
24
# File 'lib/string_extensions.rb', line 22

def capitalize_words
 split(/\b/).map{|x| x.capitalize }.join
end

#decrement(step = 1) ⇒ Object

Decrement the rightmost integer in a string, if any

cf. String#succ cf. String#prev



38
39
40
# File 'lib/string_extensions.rb', line 38

def decrement(step=1)
 sub(/(.*)(\d+)/){|s| $1+((($2.to_i)-step).to_s) }    
end

#increment(step = 1) ⇒ Object

Increment the rightmost integer in a string, if any

cf. String#succ cf. String#prev



30
31
32
# File 'lib/string_extensions.rb', line 30

def increment(step=1)
 sub(/(.*)(\d+)/){|s| $1+((($2.to_i)+step).to_s) }    
end

#prevObject Also known as: pred

Return the previous string

c.f. String#next

==Examples '888'.prev => '887' 'n'.prev => 'm' 'N'.prev => 'M'

==Examples with carry '880'.prev => '879' 'nna'.prev => 'nmz' 'NNA'.prev => 'NMZ' 'nn0aA'.prev => 'nm9zZ'



82
83
84
# File 'lib/string_extensions.rb', line 82

def prev
 self.clone.prev!
end

#prev!Object Also known as: pred!

Do String#prev in place



87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/string_extensions.rb', line 87

def prev!
 return self if length==0
 i=length-1 # rightmost
 while true do
  c=self[i].chr
  prev_c,changed_flag,carry_flag=String.prev_char(c)
   return self if !changed_flag
  self[i]=prev_c
  return self if !carry_flag
  i-=1
  return nil if i<0
 end
end

#split_tabObject



18
19
20
# File 'lib/string_extensions.rb', line 18

def split_tab
 split(/\t/)
end

#wordsObject



14
15
16
# File 'lib/string_extensions.rb', line 14

def words
 split(/\W*\b\W*/)
end