Class: String

Inherits:
Object show all
Defined in:
lib/more_ruby/string.rb

Instance Method Summary collapse

Instance Method Details

#append(s) ⇒ Object



180
181
182
# File 'lib/more_ruby/string.rb', line 180

def append(s)
    self << s
end

#camelcaseObject



75
76
77
78
# File 'lib/more_ruby/string.rb', line 75

def camelcase
    s = self.pascalcase
    s[0].downcase + s[1 .. -1]
end

#capitalize_allObject



24
25
26
# File 'lib/more_ruby/string.rb', line 24

def capitalize_all
    downcase.scan(/[a-z0-9]+/).map { |z| z.capitalize }.join(' ')
end

#capitalize_first_letter_onlyObject

.capitalize will upcase the first letter and lowercase everything else; this method does only the upcase part



5
6
7
8
# File 'lib/more_ruby/string.rb', line 5

def capitalize_first_letter_only
    return self if empty?
    return self[0].upcase + self[1 .. -1] # self[1 .. -1] will return "" if self is only one character long

end

#escapeObject

Returns new string, does not modify in place



11
12
13
# File 'lib/more_ruby/string.rb', line 11

def escape
    Regexp.escape(self)
end

#escape_whitespaceObject

Within the string, whitespace chars (n, r, t) are replaced by their text equivalents, e.g. n => \n Does not modify self



240
241
242
243
244
245
246
# File 'lib/more_ruby/string.rb', line 240

def escape_whitespace
    copy = self.dup
    copy.gsub!("\n", "\\n")
    copy.gsub!("\r", "\\r")
    copy.gsub!("\t", "\\t")
    copy
end

#extract_values_from_xml_stringObject

Take the XML-string and remove from it anything that looks like an XML tag



224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/more_ruby/string.rb', line 224

def extract_values_from_xml_string
    values = []
    a = self.split("<").collect { |z| z.chomp } # need to remove whitespace where possible

    # Now remove from the array any items that end in a > - these items look like fragments of tags

    a.delete_if { |z| z =~ />$/ }

    # a might now contain nils, "" and items like "foo>bar"

    a.delete_if { |z| z == "" }
    a.compact!
    a.each { |z| values << z.split(">")[1] }

    values
end

#formatted_number(separator = ",", count_limit = 3) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/more_ruby/string.rb', line 206

def formatted_number(separator = ",", count_limit = 3)
    copy = self.dup
    s = ""
    count = 0
    while copy.size > 0
        if count == count_limit
            s << separator
            count = 0
        else
            count += 1
            s << copy[-1]
            copy.chop!
        end
    end
    s.reverse
end

#index_of_last_capitalObject

Returns the index of the last capital in the string (if one exists)



55
56
57
58
59
60
# File 'lib/more_ruby/string.rb', line 55

def index_of_last_capital
    pos = 0
    reverse_index = self.reverse.index /[A-Z]/
    return nil if reverse_index == nil
    self.size - reverse_index - 1
end

#invert_caseObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/more_ruby/string.rb', line 28

def invert_case
    s = ""
    self.chars do |c|
        if c =~ /[A-Z]/
            s << c.downcase
        elsif c =~ /[a-z]/
            s << c.upcase
        else
            s << c
        end            
    end
    raise "invert_case failed!" unless s.size == self.size
    s
end

#is_hex?Boolean

Does the string look like hex? !! will convrt nil to false, and anythig else (e.g. 0) to true

Returns:

  • (Boolean)


202
203
204
# File 'lib/more_ruby/string.rb', line 202

def is_hex?
    !!(self =~ /^[0-9a-fA-F]+$/)
end

#is_integer?Boolean

Does the string look like an integer? !! will convrt nil to false, and anythig else (e.g. 0) to true

Returns:

  • (Boolean)


196
197
198
# File 'lib/more_ruby/string.rb', line 196

def is_integer?
    !!(self =~ /^[0-9]+$/)
end

#join(s = "") ⇒ Object



184
185
186
# File 'lib/more_ruby/string.rb', line 184

def join(s = "")
    append(s)
end

#pascalcaseObject

Like camelcase but with the first letter also capitalised Pascalcase is C#‘s case convention



71
72
73
# File 'lib/more_ruby/string.rb', line 71

def pascalcase
    downcase.scan(/[a-z0-9]+/).map { |x| x.capitalize }.join
end

#prefix_lines(prefix) ⇒ Object

Prefixes each line with the supplied string



44
45
46
# File 'lib/more_ruby/string.rb', line 44

def prefix_lines(prefix)
    gsub(/^/) { prefix }
end

#random_caseObject

Returns a new string with each character’s case randomised



16
17
18
19
20
21
22
# File 'lib/more_ruby/string.rb', line 16

def random_case
    new = ""
    self.each_char do |x|
        new << ((rand(2) % 2 == 0) ? x.upcase : x.downcase)
    end
    new
end

#snakecaseObject

Converts aStringInCamelCase to a_string_in_camel_case Also converts SomeStringInPascalCase to some_string_in_pascal_case a << => “thiNGS-with_stuff”, :expected => “thi_ngs_with_stuff”



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/more_ruby/string.rb', line 83

def snakecase
    # Notes : 

    # If the entire string contains only uppercase (with or without underscores), return it as it is

    if self =~ /^[A-Z_]+$/
        return self
    end

    # If the entire string contains only uppercase and numbers, AND has underscores, return it as it is

    # REQ_ID2 -> REQ_ID2 ; REQID2 should not -> REQID2

    if self =~ /^[A-Z0-9_]+$/ && self.include?("_")
        return self
    end

    a = []

    before = self.snakecase_non_alpha
    parts = before.split("_")
    
    # Process each part, then stitch them back together

    # Each part might itself contain several 'camel humps' 

    # Each fragment within each part might be of different 'format'


    parts.each do |part|
        # If the part is already all lowercase, keep it and move on to the next part

        part =~ /^([a-z0-9]+)$/
        if $1
            a << $1
            next
        end
        
        # ABC -> ABC # if all capitals, leave it as it is

        # If the part is already all uppercase, keep it and move on to the next part

        part =~ /^([A-Z]+)$/
        if $1
            a << $1
            next
        end

        #

        # The part contains 'camel humps', which need to be processed

        #


        # Make sure to preserve the leading part of the string before the first 'hump'

        part =~ /^([a-z0-9]+)([A-Z])/
        if $1
            a << $1
        end

        # This scan-regex will only match from the first 'hump' onwards

        fragments = part.scan /([A-Z]+[a-z0-9]*)/
        fragments.flatten!
        fragments.each do |fragment|

            # ABCD -> abcd

            fragment =~ /^([A-Z]+)$/
            if $1
                a << $1.downcase
                next
            end

            # ABCD1234 -> abcd_1234

            fragment =~ /^([A-Z]+)([0-9]+)$/
            if $1
                a << $1.downcase
                a << $2
                next
            end
            
            # Abc -> abc

            fragment =~ /^([A-Z][a-z0-9]*)$/
            if $1
                a << $1.downcase
                next
            end
            
            # ABCDef -> abc_def

            fragment =~ /^([A-Z]+)([A-Z][a-z0-9]*)$/
            if $1
                a << $1.downcase
                a << $2.downcase
                next
            end

        end # end fragments

    end # end parts

    s = a.join("_")

    # Final tidying

    s.gsub!(/[_]+/, "_") # replace continuous underscores with one underscore

    s = s[1 .. -1] if s[0] == "_" # a pascalcase string will cause a leading underscore, which we need to remove

    s
end

#snakecase_and_downcaseObject



176
177
178
# File 'lib/more_ruby/string.rb', line 176

def snakecase_and_downcase
    self.snakecase.downcase
end

#snakecase_non_alphaObject

Changes every sequence of non-alpha-numeric characters to underscores If you want to convert something looking like camelcase to snakecase, use snakecase



65
66
67
# File 'lib/more_ruby/string.rb', line 65

def snakecase_non_alpha
    gsub(/[^a-zA-Z0-9]+/, '_')
end

#to_boolObject



188
189
190
191
192
# File 'lib/more_ruby/string.rb', line 188

def to_bool
    return true if self.downcase == "true"
    return false if self.downcase == "false"
    raise "String #{self} was neither 'true' nor 'false'. Cannot convert to boolean in this custom method."
end

#unindentObject

Remove leading whitespace from each line in the string, using the indentation of the first line as the guide



49
50
51
52
# File 'lib/more_ruby/string.rb', line 49

def unindent
    leading_whitespace = self[/\A\s*/]
    self.gsub(/^#{leading_whitespace}/, '')
end