Class: String

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

Instance Method Summary collapse

Instance Method Details

#acronymObject



36
37
38
# File 'lib/lite/ruby/string.rb', line 36

def acronym
  dup.acronym!
end

#acronym!Object



40
41
42
# File 'lib/lite/ruby/string.rb', line 40

def acronym!
  gsub!(/(([a-zA-Z0-9])([a-zA-Z0-9])*)./, '\\2') || self
end

#any?(*keys) ⇒ Boolean

Returns:

  • (Boolean)


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

def any?(*keys)
  keys.any? { |key| include?(key) }
end

#at(position) ⇒ Object



48
49
50
# File 'lib/lite/ruby/string.rb', line 48

def at(position)
  self[position]
end

#camelize(first_letter = :upper) ⇒ Object Also known as: camelcase



52
53
54
55
56
57
# File 'lib/lite/ruby/string.rb', line 52

def camelize(first_letter = :upper)
  case first_letter
  when :upper, true then modulize.gsub(/(\A|\s)([a-z])/) { $1 + $2.upcase }
  when :lower, false then modulize.gsub(/(\A|\s)([A-Z])/) { $1 + $2.downcase }
  end || modulize
end

#camelize!(first_letter = :upper) ⇒ Object Also known as: camelcase!



61
62
63
# File 'lib/lite/ruby/string.rb', line 61

def camelize!(first_letter = :upper)
  replace(camelize(first_letter))
end

#capitalized?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/lite/ruby/string.rb', line 67

def capitalized?
  capitalize == self
end

#classifyObject



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

def classify
  dup.classify!
end

#classify!Object



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

def classify!
  sub!(/.*\./, '')
  camelize!
end

#constantizeObject



80
81
82
# File 'lib/lite/ruby/string.rb', line 80

def constantize
  Object.const_get(camelize)
end

#dasherizeObject



84
85
86
# File 'lib/lite/ruby/string.rb', line 84

def dasherize
  underscore.tr('_', '-')
end

#dasherize!Object



88
89
90
# File 'lib/lite/ruby/string.rb', line 88

def dasherize!
  replace(dasherize)
end

#deconstantizeObject



92
93
94
# File 'lib/lite/ruby/string.rb', line 92

def deconstantize
  [0, rindex('::') || 0]
end

#deconstantize!Object



96
97
98
# File 'lib/lite/ruby/string.rb', line 96

def deconstantize!
  replace(deconstantize)
end

#dedupe(pattern) ⇒ Object



100
101
102
# File 'lib/lite/ruby/string.rb', line 100

def dedupe(pattern)
  dup.dedupe!(pattern)
end

#dedupe!(pattern) ⇒ Object



104
105
106
107
# File 'lib/lite/ruby/string.rb', line 104

def dedupe!(pattern)
  pattern.each_char { |char| gsub!(/#{Regexp.escape(char)}{2,}/, char) }
  self
end

#demodulizeObject



109
110
111
# File 'lib/lite/ruby/string.rb', line 109

def demodulize
  gsub(/^.*::/, '')
end

#demodulize!Object



113
114
115
# File 'lib/lite/ruby/string.rb', line 113

def demodulize!
  replace(demodulize)
end

#domainObject



117
118
119
120
121
# File 'lib/lite/ruby/string.rb', line 117

def domain
  return self unless self =~ %r{^(?:\w+://)?([^/?]+)(?:/|\?|$)}

  Regexp.last_match(1)
end

#downcase?Boolean

Returns:

  • (Boolean)


123
124
125
# File 'lib/lite/ruby/string.rb', line 123

def downcase?
  downcase == self
end

#each_word(&block) ⇒ Object



127
128
129
# File 'lib/lite/ruby/string.rb', line 127

def each_word(&block)
  words.each(&block)
end

#ellipsize(ellipsize_at, options = {}) ⇒ Object



131
132
133
134
135
136
137
138
# File 'lib/lite/ruby/string.rb', line 131

def ellipsize(ellipsize_at, options = {})
  return self if length <= ellipsize_at

  separator = options[:separator] || '...'
  offset = options[:offset] || 4

  "#{self[0, offset]}#{separator}#{self[-offset, offset]}"
end

#first(limit = 1) ⇒ Object



140
141
142
143
144
145
146
147
148
# File 'lib/lite/ruby/string.rb', line 140

def first(limit = 1)
  if limit.zero?
    ''
  elsif limit >= length
    self
  else
    to(limit - 1)
  end
end

#format(*args) ⇒ Object



150
151
152
# File 'lib/lite/ruby/string.rb', line 150

def format(*args)
  super(self, *args.flatten)
end

#from(position) ⇒ Object



154
155
156
# File 'lib/lite/ruby/string.rb', line 154

def from(position)
  self[position..-1]
end

#headerizeObject



158
159
160
# File 'lib/lite/ruby/string.rb', line 158

def headerize
  squish.each_word(&:capitalize!).join(' ')
end

#headerize!Object



162
163
164
# File 'lib/lite/ruby/string.rb', line 162

def headerize!
  replace(headerize)
end

#humanize(options = {}) ⇒ Object



166
167
168
# File 'lib/lite/ruby/string.rb', line 166

def humanize(options = {})
  dup.humanize!(options)
end

#humanize!(capitalize: true) ⇒ Object



170
171
172
173
174
175
176
177
# File 'lib/lite/ruby/string.rb', line 170

def humanize!(capitalize: true)
  underscore!
  gsub!(/_id\z/, '')
  tr!('_', ' ')
  squish!
  gsub!(/([a-z\d]*)/i, &:downcase)
  gsub!(/\A\w/) { |str| capitalize ? str.upcase : str } || self
end

#indent(amount, seperator = ' ') ⇒ Object



179
180
181
# File 'lib/lite/ruby/string.rb', line 179

def indent(amount, seperator = ' ')
  dup.indent!(amount, seperator)
end

#indent!(amount, seperator = ' ') ⇒ Object



183
184
185
186
187
188
189
# File 'lib/lite/ruby/string.rb', line 183

def indent!(amount, seperator = ' ')
  if amount >= 0
    gsub!(/^/, seperator * amount)
  else
    gsub!(/^#{Regexp.escape(seperator)}{0,#{-amount}}/, '')
  end
end

#index_all(pattern) ⇒ Object



191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/lite/ruby/string.rb', line 191

def index_all(pattern)
  pattern = pattern.to_s if pattern.is_a?(Numeric)
  arr_indexes = []
  srch_index = rindex(pattern)

  while srch_index
    temp_string = self[0..(srch_index - 1)]
    arr_indexes << srch_index
    srch_index = srch_index.zero? ? nil : temp_string.rindex(pattern)
  end

  arr_indexes.reverse
end

#labelize(capitalize: true) ⇒ Object Also known as: labelcase



205
206
207
# File 'lib/lite/ruby/string.rb', line 205

def labelize(capitalize: true)
  dup.labelize!(capitalize: capitalize)
end

#labelize!(capitalize: true) ⇒ Object Also known as: labelcase!



211
212
213
214
215
216
217
218
# File 'lib/lite/ruby/string.rb', line 211

def labelize!(capitalize: true)
  underscore!
  tr!('_', ' ')
  squish!
  gsub!(/([a-z\d]*)/i, &:downcase)
  gsub!(/\A\w/) { |str| capitalize ? str.upcase : str }
  gsub!(/ id\z/, ' ID') || self
end

#last(limit = 1) ⇒ Object



222
223
224
225
226
227
228
229
230
# File 'lib/lite/ruby/string.rb', line 222

def last(limit = 1)
  if limit.zero?
    ''
  elsif limit >= length
    self
  else
    from(-limit)
  end
end

#lchomp(match) ⇒ Object



232
233
234
# File 'lib/lite/ruby/string.rb', line 232

def lchomp(match)
  dup.lchomp!(match)
end

#lchomp!(match) ⇒ Object



236
237
238
239
240
241
# File 'lib/lite/ruby/string.rb', line 236

def lchomp!(match)
  return self unless index(match)

  self[0...match.size] = ''
  self
end

#methodizeObject



243
244
245
# File 'lib/lite/ruby/string.rb', line 243

def methodize
  dup.methodize!
end

#methodize!Object



247
248
249
250
251
252
253
# File 'lib/lite/ruby/string.rb', line 247

def methodize!
  gsub!(/([A-Z]+)([A-Z])/, '\1_\2')
  gsub!(/([a-z])([A-Z])/, '\1_\2')
  gsub!('/', '__')
  gsub!('::', '__')
  downcase! || self
end

#mixedcase?Boolean

Returns:

  • (Boolean)


266
267
268
# File 'lib/lite/ruby/string.rb', line 266

def mixedcase?
  !upcase? && !downcase?
end

#modulizeObject



255
256
257
# File 'lib/lite/ruby/string.rb', line 255

def modulize
  dup.modulize!
end

#modulize!Object



259
260
261
262
263
264
# File 'lib/lite/ruby/string.rb', line 259

def modulize!
  gsub!(/__(.?)/) { "::#{$1.upcase}" }
  gsub!(%r{/(.?)}) { "::#{$1.upcase}" }
  gsub!(/(?:_+|-+)([a-z])/) { $1.upcase }
  gsub!(/(\A|\s)([a-z])/) { $1 + $2.upcase } || self
end

#non_possessiveObject



314
315
316
# File 'lib/lite/ruby/string.rb', line 314

def non_possessive
  dup.non_possessive!
end

#non_possessive!Object



318
319
320
321
322
# File 'lib/lite/ruby/string.rb', line 318

def non_possessive!
  return self unless possessive?

  chomp!("'s") || chomp!("'") || self
end

#ordinalObject



270
271
272
# File 'lib/lite/ruby/string.rb', line 270

def ordinal
  to_i.ordinal
end

#ordinalizeObject



274
275
276
# File 'lib/lite/ruby/string.rb', line 274

def ordinalize
  to_i.ordinalize
end

#parameterize(separator: '-') ⇒ Object



278
279
280
# File 'lib/lite/ruby/string.rb', line 278

def parameterize(separator: '-')
  dup.parameterize!(separator: separator)
end

#parameterize!(separator: '-') ⇒ Object



282
283
284
285
286
# File 'lib/lite/ruby/string.rb', line 282

def parameterize!(separator: '-')
  underscore!
  gsub!(/\s+/, separator)
  downcase! || self
end

#pathizeObject



288
289
290
# File 'lib/lite/ruby/string.rb', line 288

def pathize
  dup.pathize!
end

#pathize!Object



292
293
294
295
296
297
298
299
300
# File 'lib/lite/ruby/string.rb', line 292

def pathize!
  gsub!(/([A-Z]+)([A-Z])/, '\1_\2')
  gsub!(/([a-z])([A-Z])/, '\1_\2')
  gsub!('__', '/')
  gsub!('::', '/')
  gsub!(/\s+/, '')
  gsub!(/[?%*:|"<>.]+/, '')
  downcase! || self
end

#pollute(delimiter = '^--^--^') ⇒ Object



302
303
304
# File 'lib/lite/ruby/string.rb', line 302

def pollute(delimiter = '^--^--^')
  chars.map { |chr| "#{chr}#{delimiter}" }.join
end

#pollute!(delimiter = '^--^--^') ⇒ Object



306
307
308
# File 'lib/lite/ruby/string.rb', line 306

def pollute!(delimiter = '^--^--^')
  replace(pollute(delimiter))
end

#popObject



310
311
312
# File 'lib/lite/ruby/string.rb', line 310

def pop
  self[-1]
end

#possessiveObject



324
325
326
327
328
329
# File 'lib/lite/ruby/string.rb', line 324

def possessive
  return self if possessive?

  possession = end_with?('s') ? "'" : "'s"
  "#{self}#{possession}"
end

#possessive!Object



331
332
333
# File 'lib/lite/ruby/string.rb', line 331

def possessive!
  replace(possessive)
end

#possessive?Boolean

Returns:

  • (Boolean)


335
336
337
# File 'lib/lite/ruby/string.rb', line 335

def possessive?
  %w['s s'].any? { |pos| end_with?(pos) }
end

#push(string) ⇒ Object



339
340
341
# File 'lib/lite/ruby/string.rb', line 339

def push(string)
  replace(concat(string))
end

#quote(type = :double, amount = nil) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/lite/ruby/string.rb', line 344

def quote(type = :double, amount = nil)
  if type.is_a?(Integer)
    tmp = amount
    amount = type
    type = tmp || :mixed
  else
    amount ||= 1
  end

  case type.to_s
  when "'", 'single', 's', '1'
    f = "'" * amount
    b = f
  when '"', 'double', 'd', '2'
    f = '"' * amount
    b = f
  when '`', 'back', 'backtick', 'b', '-1'
    f = '`' * amount
    b = f
  when "`'", 'bracket', 'sb'
    f = '`' * amount
    b = "'" * amount
  when "'\"", 'mixed', 'm', 'Integer'
    c = (amount.to_f / 2).to_i
    f = '"' * c
    b = f

    if amount.odd?
      f = "'" + f
      b += "'"
    end
  else
    raise ArgumentError, "Invalid quote type: #{type.inspect}"
  end

  "#{f}#{self}#{b}"
end

#quote!(type = :double, amount = nil) ⇒ Object

rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength



383
384
385
# File 'lib/lite/ruby/string.rb', line 383

def quote!(type = :double, amount = nil)
  replace(quote(type, amount))
end

#remove(*patterns) ⇒ Object



387
388
389
# File 'lib/lite/ruby/string.rb', line 387

def remove(*patterns)
  dup.remove!(*patterns)
end

#remove!(*patterns) ⇒ Object



391
392
393
394
395
# File 'lib/lite/ruby/string.rb', line 391

def remove!(*patterns)
  patterns.each_with_object(self) do |pat, str|
    pat.is_a?(Range) ? str.slice!(pat) : str.gsub!(pat, '')
  end
end

#remove_tagsObject



397
398
399
# File 'lib/lite/ruby/string.rb', line 397

def remove_tags
  dup.remove_tags!
end

#remove_tags!Object



401
402
403
# File 'lib/lite/ruby/string.rb', line 401

def remove_tags!
  gsub!(%r{</?[^>]*>}, '') || self
end

#rotate(amount = 1) ⇒ Object



405
406
407
# File 'lib/lite/ruby/string.rb', line 405

def rotate(amount = 1)
  dup.rotate!(amount)
end

#rotate!(amount = 1) ⇒ Object



409
410
411
412
# File 'lib/lite/ruby/string.rb', line 409

def rotate!(amount = 1)
  amount += size if amount.negative?
  slice!(amount, size - amount) + slice!(0, amount)
end

#safe_encode(target_encoding, replacement = '') ⇒ Object

rubocop:disable Metrics/MethodLength



415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'lib/lite/ruby/string.rb', line 415

def safe_encode(target_encoding, replacement = '')
  encode(target_encoding)
rescue Encoding::InvalidByteSequenceError
  force_encoding(target_encoding).scrub!(replacement)
rescue Encoding::UndefinedConversionError
  encode(
    target_encoding,
    invalid: :replace,
    undef: :replace,
    replace: replacement,
    UNIVERSAL_NEWLINE_DECORATOR: true
  )
end

#safe_encode!(target_encoding, replacement = '') ⇒ Object

rubocop:enable Metrics/MethodLength



430
431
432
# File 'lib/lite/ruby/string.rb', line 430

def safe_encode!(target_encoding, replacement = '')
  replace(safe_encode(target_encoding, replacement))
end

#sample(separator = ' ') ⇒ Object



434
435
436
# File 'lib/lite/ruby/string.rb', line 434

def sample(separator = ' ')
  split(separator).sample
end

#sample!(separator = ' ') ⇒ Object



438
439
440
# File 'lib/lite/ruby/string.rb', line 438

def sample!(separator = ' ')
  replace(sample(separator))
end

#shift(*patterns) ⇒ Object



442
443
444
# File 'lib/lite/ruby/string.rb', line 442

def shift(*patterns)
  dup.shift!(*patterns)
end

#shift!(*patterns) ⇒ Object



446
447
448
449
450
# File 'lib/lite/ruby/string.rb', line 446

def shift!(*patterns)
  return self[0] if patterns.empty?

  patterns.each_with_object(self) { |pat, str| str.sub!(pat, '') }
end

#shuffle(separator = '') ⇒ Object



452
453
454
# File 'lib/lite/ruby/string.rb', line 452

def shuffle(separator = '')
  split(separator).shuffle.join
end

#shuffle!(separator = '') ⇒ Object



456
457
458
# File 'lib/lite/ruby/string.rb', line 456

def shuffle!(separator = '')
  replace(shuffle(separator))
end

#sift(keep) ⇒ Object



460
461
462
463
464
465
466
467
468
469
# File 'lib/lite/ruby/string.rb', line 460

def sift(keep)
  keep = case keep
         when String then keep.chars
         when Array then keep.map(&:to_s)
         when Range then keep.to_a.map(&:to_s)
         else raise TypeError, "Invalid parameter: #{keep.inspect}"
         end

  chars.keep_if { |chr| keep.include?(chr) }.join
end

#sift!(keep) ⇒ Object



471
472
473
# File 'lib/lite/ruby/string.rb', line 471

def sift!(keep)
  replace(sift(keep))
end

#slugifyObject



475
476
477
# File 'lib/lite/ruby/string.rb', line 475

def slugify
  dup.slugify!
end

#slugify!Object



479
480
481
482
483
484
485
# File 'lib/lite/ruby/string.rb', line 479

def slugify!
  gsub!(/[^\x00-\x7F]+/, '')
  gsub!(/[^\w_ \-]+/i, '')
  gsub!(/[ \-]+/i, '-')
  gsub!(/^-|-$/i, '')
  downcase! || self
end

#sortObject



496
497
498
# File 'lib/lite/ruby/string.rb', line 496

def sort
  chars.sort.join
end

#sort!Object



500
501
502
# File 'lib/lite/ruby/string.rb', line 500

def sort!
  replace(sort)
end

#squishObject



487
488
489
# File 'lib/lite/ruby/string.rb', line 487

def squish
  dup.squish!
end

#squish!Object



491
492
493
494
# File 'lib/lite/ruby/string.rb', line 491

def squish!
  strip!
  gsub!(/\s+/, ' ') || self
end

#titleizeObject Also known as: titlecase



504
505
506
# File 'lib/lite/ruby/string.rb', line 504

def titleize
  dup.titleize!
end

#titleize!Object Also known as: titlecase!



510
511
512
513
514
# File 'lib/lite/ruby/string.rb', line 510

def titleize!
  underscore!
  humanize!
  gsub!(/\b(?<!['’`])[a-z]/) { $&.capitalize } || self
end

#to(position) ⇒ Object



518
519
520
# File 'lib/lite/ruby/string.rb', line 518

def to(position)
  self[0..position]
end

#transliterizeObject



522
523
524
# File 'lib/lite/ruby/string.rb', line 522

def transliterize
  dup.transliterize!
end

#transliterize!Object



526
527
528
# File 'lib/lite/ruby/string.rb', line 526

def transliterize!
  TRANSLITERATIONS.each_with_object(self) { |(k, v), str| str.gsub!(k, v) }
end

#truncate(truncate_at, options = {}) ⇒ Object



530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/lite/ruby/string.rb', line 530

def truncate(truncate_at, options = {})
  return dup unless length > truncate_at

  seperator = options[:separator]
  omission = options[:omission] || '...'
  size_with_room_for_omission = truncate_at - omission.length

  stop = if seperator
           rindex(seperator || '', size_with_room_for_omission) || size_with_room_for_omission
         else
           size_with_room_for_omission
         end

  "#{self[0, stop]}#{omission}"
end

#truncate_words(words_count, options = {}) ⇒ Object



546
547
548
549
550
551
552
# File 'lib/lite/ruby/string.rb', line 546

def truncate_words(words_count, options = {})
  sep = options[:separator] || /\s+/
  sep = Regexp.escape(sep.to_s) unless sep.is_a(Regexp)
  return self unless /\A((?:.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m.match?(self)

  "#{::Regexp.last_match(1)}#{options[:omissio] || '...'}"
end

#underscoreObject Also known as: snakecase



554
555
556
# File 'lib/lite/ruby/string.rb', line 554

def underscore
  dup.underscore!
end

#underscore!Object Also known as: snakecase!



560
561
562
563
564
565
566
567
# File 'lib/lite/ruby/string.rb', line 560

def underscore!
  camelize!
  gsub!(/::/, '/')
  gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
  gsub!(/([a-z\d])([A-Z])/, '\1_\2')
  tr!('-', '_')
  downcase! || self
end

#unpollute(delimiter = '^--^--^') ⇒ Object



571
572
573
# File 'lib/lite/ruby/string.rb', line 571

def unpollute(delimiter = '^--^--^')
  dup.unpollute!(delimiter)
end

#unpollute!(delimiter = '^--^--^') ⇒ Object



575
576
577
# File 'lib/lite/ruby/string.rb', line 575

def unpollute!(delimiter = '^--^--^')
  gsub!(delimiter, '') || self
end

#unquoteObject



592
593
594
# File 'lib/lite/ruby/string.rb', line 592

def unquote
  dup.unquote!
end

#unquote!Object



596
597
598
599
600
601
602
603
604
# File 'lib/lite/ruby/string.rb', line 596

def unquote!
  [0, -1].each do |i|
    case self[i, 1]
    when "'", '"', '`' then self[i] = ''
    end
  end

  self
end

#unshift(*patterns) ⇒ Object



583
584
585
586
# File 'lib/lite/ruby/string.rb', line 583

def unshift(*patterns)
  patterns.each_with_object('') { |pat, str| str << pat }
          .concat(self)
end

#unshift!(*patterns) ⇒ Object



588
589
590
# File 'lib/lite/ruby/string.rb', line 588

def unshift!(*patterns)
  replace(unshift(*patterns))
end

#upcase?Boolean

Returns:

  • (Boolean)


579
580
581
# File 'lib/lite/ruby/string.rb', line 579

def upcase?
  upcase == self
end

#variablizeObject



619
620
621
# File 'lib/lite/ruby/string.rb', line 619

def variablize
  "@#{gsub(/\W/, '_')}"
end

#variablize!Object



623
624
625
# File 'lib/lite/ruby/string.rb', line 623

def variablize!
  replace(variablize)
end

#wordsObject



606
607
608
# File 'lib/lite/ruby/string.rb', line 606

def words
  split(/\s+/)
end

#words_without_punctuationObject



610
611
612
613
614
615
616
617
# File 'lib/lite/ruby/string.rb', line 610

def words_without_punctuation
  str = dup
  str.gsub!(%r{[.?¿¡…!,::;—"。?!、‘“”„«»〈〉《》,/\[\]]}, ' ')
  str.gsub!('- ', ' ')
  str.squeeze!(' ')
  str.strip!
  str.words
end