Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/random-words/string.rb,
lib/random-words/table-cleanup.rb

Overview

String helpers

Instance Method Summary collapse

Instance Method Details

#alignment?Boolean

Returns:

  • (Boolean)


148
149
150
# File 'lib/random-words/table-cleanup.rb', line 148

def alignment?
  self =~ /^[\s|:-]+$/ ? true : false
end

#article_agreeObject



354
355
356
357
358
359
# File 'lib/random-words/string.rb', line 354

def article_agree
  gsub(/\ban? (\w)/i) do |match|
    word = match[1]
    /\A[aeiou]/i.match?(word) ? "an #{word}" : "a #{word}"
  end
end

#cap_firstString

Capitalize the first letter of a string.

Returns:

  • (String)

    The string with the first letter capitalized.



184
185
186
187
188
# File 'lib/random-words/string.rb', line 184

def cap_first
  # Capitalizes the first letter of a string.
  self[0] = self[0].upcase
  self
end

#capitalizeString

Capitalize the first letter of a string, respcting punctuation.

Examples:

"hello world".capitalize # => "Hello world"

Returns:

  • (String)

    The string with the first letter capitalized.



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/random-words/string.rb', line 59

def capitalize
  return self if empty?

  str = dup

  debug = ''
  str.sub!(/^%[A-Z]+%/) do |match|
    debug = match
    ''
  end

  letters = str.split('')
  string = []
  string << letters.shift while letters[0] !~ /[[:word:]]/
  string << letters.shift.upcase
  string.concat(letters)
  debug + string.join('')
end

#capitalize_iString

Capitalize instances of “i” in a string.

Examples:

"this is an i".capitalize_i # => "this is an I"
"this is an iPhone".capitalize_i # => "this is an iPhone"

Returns:

  • (String)

    The string with “i” capitalized.



51
52
53
# File 'lib/random-words/string.rb', line 51

def capitalize_i
  gsub(/\bi\b/, 'I')
end

#cleanString

Remove unwanted characters and whitespace from a string.

Examples:

"Hello, World!".clean # => "Hello World"

Returns:

  • (String)

    The string with unwanted characters removed.

  • (String)

    The cleaned string.



40
41
42
# File 'lib/random-words/string.rb', line 40

def clean
  gsub(/[^-a-zA-Z0-9\s]/, '').strip
end

#clean_encodeString

Get a clean UTF-8 string by forcing an ISO encoding and then re-encoding

Returns:



21
22
23
# File 'lib/random-words/string.rb', line 21

def clean_encode
  force_encoding('ISO-8859-1').encode('utf-8', replace: nil)
end

#clean_encode!String

Destructive version of #clean_encode

Returns:

  • (String)

    UTF-8 string, in place



30
31
32
# File 'lib/random-words/string.rb', line 30

def clean_encode!
  replace clean_encode
end

#clean_outputObject



361
362
363
# File 'lib/random-words/string.rb', line 361

def clean_output
  encode('iso-8859-1', undef: :replace, invalid: :replace, replace: '').force_encoding('UTF-8')
end

#colorize_text(text, color, testing: false) ⇒ String

Colorize the text for terminal output. If the output is not a TTY, the text is returned without colorization.

Examples:

colorize_text("Hello, World!", :red) # => "\e[31mHello, World!\e[0m"

Parameters:

  • text (String)

    The text to colorize.

  • color (Symbol)

    The color to use (e.g., :red, :green).

Returns:

  • (String)

    The colorized text.



303
304
305
306
307
308
309
310
311
312
313
# File 'lib/random-words/string.rb', line 303

def colorize_text(text, color, testing: false)
  return text if !$stdout.isatty && !testing

  return text unless colors.key?(color)

  return text if text.empty?

  color_code = colors[color]

  "\e[#{color_code}m#{text}\e[0m"
end

#colorsObject

Terminal output colors



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/random-words/string.rb', line 272

def colors
  {
    black: 30,
    red: 31,
    green: 32,
    yellow: 33,
    blue: 34,
    magenta: 35,
    cyan: 36,
    white: 37,
    boldblack: '1;30',
    boldred: '1;31',
    boldgreen: '1;32',
    boldyellow: '1;33',
    boldblue: '1;34',
    boldmagenta: '1;35',
    boldcyan: '1;36',
    boldwhite: '1;37',
    reset: 0
  }
end

#compressString

Compress multiple spaces into a single space and remove leading/trailing spaces.

Returns:

  • (String)

    The string with extra spaces compressed.



140
141
142
# File 'lib/random-words/string.rb', line 140

def compress
  gsub(/\s+/, ' ').strip
end

#compress_newlinesString

Remove extra newlines from the output.

Returns:

  • (String)

    The string with extra newlines removed.



200
201
202
203
# File 'lib/random-words/string.rb', line 200

def compress_newlines
  # Removes extra newlines from the output.
  gsub(/\n{2,}/, "\n\n").strip
end

#compress_newlines!String

Compress newlines in the output, destructive.

Returns:

  • (String)

    The string with newlines compressed.

See Also:



208
209
210
211
# File 'lib/random-words/string.rb', line 208

def compress_newlines!
  # Removes extra newlines from the output.
  replace compress_newlines
end

#dedup_punctuationString

Remove duplicate punctuation

Examples:

"Hello, , World!".dedup_punctuation # => "Hello, World!"

Returns:

  • (String)

    The string with duplicate punctuation removed.



116
117
118
# File 'lib/random-words/string.rb', line 116

def dedup_punctuation
  gsub(/((%[A-Z]+%)?[,.;:—] ?)+/, '\1').gsub(/([,;:—])/, '\1')
end

#downcase_firstString

Downcase the first letter of a string, respecting punctuation.

Returns:

  • (String)

    The string with the first letter downcased.



80
81
82
83
84
85
86
87
88
89
# File 'lib/random-words/string.rb', line 80

def downcase_first
  return self if empty?

  letters = split('')
  string = []
  string << letters.shift while letters[0] !~ /[[:word:]]/
  string << letters.shift.downcase
  string.concat(letters)
  string.join('')
end

#ensure_pipesString

Ensure leading and trailing pipes

Returns:

  • (String)

    string with pipes



144
145
146
# File 'lib/random-words/table-cleanup.rb', line 144

def ensure_pipes
  strip.gsub(/^\|?(.*?)\|?$/, '|\1|')
end

#expand_debug(testing: false) ⇒ String

Expand abbreviated debug statements in the string.

Returns:

  • (String)

    The expanded debug string.



344
345
346
347
348
349
350
351
352
# File 'lib/random-words/string.rb', line 344

def expand_debug(testing: false)
  gsub(/%(#{Regexp.union(expansions.keys)})%?/) do
    match = Regexp.last_match

    return match unless expansions.key?(match[1])

    colorize_text("[#{expansions[match[1]][0] || match}]", expansions[match[1]][1] || :white, testing: testing)
  end
end

#expansionsObject

Dictionary of expansions



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/random-words/string.rb', line 316

def expansions
  {
    'ADJ' => ['Adjective', :yellow],
    'ADV' => ['Adverb', :boldyellow],
    'ART' => ['Article', :cyan],
    'CLA' => ['Clause', :magenta],
    'COC' => ['Coordinating Conjunction', :magenta],
    'CON' => ['Conjunction', :magenta],
    'NAM' => ['Name', :boldblue],
    'NOU' => ['Noun', :green],
    'NUM' => ['Number', :red],
    'PAV' => ['Passive Verb', :boldred],
    'PHR' => ['Phrase', :boldcyan],
    'PLA' => ['Plural Article', :yellow],
    'PLN' => ['Plural Noun', :green],
    'PLV' => ['Plural Verb', :boldred],
    'PNO' => ['Proper Noun', :boldblack],
    'PRE' => ['Preposition', :boldwhite],
    'PRP' => ['Prepositional Phrase', :boldwhite],
    'SEP' => ['Separator', :red],
    'SUC' => ['Subordinate Conjunction', :magenta],
    'TER' => ['Terminator', :boldcyan],
    'VER' => ['Verb', :boldred]
  }
end

#fix_caps(terminators) ⇒ String

Capitalize the first letter of each sentence in a string. Scans for all known terminators followed by a space and capitalizes the next letter.

Examples:

"hello world. this is a test.".fix_caps([[".", "."]]) # => "Hello world. This is a test."

Parameters:

  • terminators (Array<Array>)

    An array of beginning and ending punctuation mark arrays.

Returns:

  • (String)

    The string with the first letter of each sentence capitalized.



98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/random-words/string.rb', line 98

def fix_caps(terminators)
  return self if empty?

  terminator_ends = terminators.map { |t| t[1].split('').last }.delete_if(&:empty?)
  return capitalize if terminator_ends.empty?

  terminator_regex = Regexp.new("[#{Regexp.escape(terminator_ends.join)}]")
  return capitalize unless match?(terminator_regex)

  split(/(?<=#{terminator_regex}) /).map do |sentence|
    sentence.capitalize
  end.join(' ')
end

#indent(string) ⇒ String

Indent every line in a string with a specified string.

Parameters:

  • string (String)

    The string to indent with.

Returns:

  • (String)

    The indented string.



178
179
180
# File 'lib/random-words/string.rb', line 178

def indent(string)
  gsub(/^/, string)
end

#no_term(terminators) ⇒ String

Remove any punctuation mark from the end of a string.

Returns:

  • (String)

    The string with the last punctuation mark removed.



162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/random-words/string.rb', line 162

def no_term(terminators)
  str = dup
  leading = terminators.map { |t| t[0] }.delete_if(&:empty?).sort.uniq.join
  trailing = terminators.map { |t| t[1] }.delete_if(&:empty?).sort.uniq.join
  return self if leading.empty? && trailing.empty?

  str.gsub!(/[#{Regexp.escape(leading)}]+/, '') unless leading.empty?

  str.gsub!(/[#{Regexp.escape(trailing)}]+/, '') unless trailing.empty?

  str
end

#preserve_spacesString

Preserve spaces in the output by replacing multiple spaces with %%.

Returns:

  • (String)

    The string with spaces preserved.



215
216
217
218
# File 'lib/random-words/string.rb', line 215

def preserve_spaces
  # Preserves spaces in the output.
  gsub(/ +/, '%%')
end

#restore_spacesString

Restore spaces in the output by replacing %% with spaces.

Returns:

  • (String)

    The string with spaces restored.



222
223
224
225
# File 'lib/random-words/string.rb', line 222

def restore_spaces
  # Restores spaces in the output.
  gsub('%%', ' ')
end

#split_linesArray<String>

Split a string by newlines, clean each line, and remove empty lines.

Examples:

"Hello, World!\n\nThis is a test.".split_lines # => ["Hello World", "This is a test"]

Returns:

  • (Array<String>)

    The string split into lines, cleaned, and empty lines removed.



132
133
134
135
136
# File 'lib/random-words/string.rb', line 132

def split_lines
  arr = strip.split("\n").map(&:clean)
  arr.reject!(&:empty?)
  arr
end

#term(char = '.') ⇒ String

Add a specified character to the end of a string, avoiding repeated punctuation.

Parameters:

  • char (String) (defaults to: '.')

    The character to add (default: ‘.’).

Returns:

  • (String)

    The string with the specified character at the end.



193
194
195
196
# File 'lib/random-words/string.rb', line 193

def term(char = '.')
  # Adds a specified character to the end of a string.
  sub(/[.?!,;]?$/, "#{char}")
end

#terminate(terminator) ⇒ String

Terminate a string with a random punctuation mark.

Examples:

"Hello World".terminate(["", "."]) # => "Hello World."

Parameters:

  • terminator (Array<String>)

    An array of beginning and ending punctuation marks.

Returns:

  • (String)

    The string with a random punctuation mark at the end.



150
151
152
153
154
155
156
157
158
# File 'lib/random-words/string.rb', line 150

def terminate(terminator)
  debug = ''
  str = dup
  str.sub!(/^%[A-Z]+%/) do |match|
    debug = match
    ''
  end
  debug + str.sub(/^/, terminator[0]).sub(/[^a-zA-Z0-9]*$/, terminator[1])
end

#to_lengthSymbol

Convert the string to a length symbol based on its name.

Returns:

  • (Symbol)

    The symbolized length of the string.



256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/random-words/string.rb', line 256

def to_length
  case self
  when /^s/i
    :short
  when /^m/i
    :medium
  when /^l/i
    :long
  when /^v/i
    :very_long
  else
    :medium
  end
end

#to_sent(terminator) ⇒ String

Generate a sentence with capitalization and terminator

Parameters:

  • terminator (Array<String>)

    An array of beginning and ending punctuation marks.

Returns:

  • (String)

    The string with a random punctuation mark at the end.



123
124
125
# File 'lib/random-words/string.rb', line 123

def to_sent(terminator)
  capitalize.compress.capitalize_i.dedup_punctuation.terminate(terminator)
end

#to_sourceSymbol

Convert the string to a source symbol based on its name.

Returns:

  • (Symbol)

    The symbolized name of the source.



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/random-words/string.rb', line 235

def to_source
  new_source = nil
  sources = RandomWords::Generator.new.sources

  return sources.map { |k, v| v.name }.sample if /^(random|any)$/i.match?(self)

  sources.each do |_k, v|
    v.names.each do |name|
      next unless /^#{self}/i.match?(name.to_s)

      new_source = v.name
      break
    end
    break if new_source
  end

  new_source || :latin
end

#trueish?Boolean

Check if the string is trueish (starts with ‘t’, ‘y’, or ‘1’).

Returns:

  • (Boolean)

    true if the string is trueish, false otherwise.



229
230
231
# File 'lib/random-words/string.rb', line 229

def trueish?
  to_s =~ /^[ty1]/i
end