Class: String

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

Instance Method Summary collapse

Instance Method Details

#acronymObject



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

def acronym
  dup.acronym!
end

#acronym!Object



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

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

#any?(*keys) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#ascii_only(alt = '') ⇒ Object



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

def ascii_only(alt = '')
  dup.ascii_only!(alt)
end

#ascii_only!(alt = '') ⇒ Object



51
52
53
# File 'lib/lite/ruby/string.rb', line 51

def ascii_only!(alt = '')
  encode_only!('ASCII', alt)
end

#at(position) ⇒ Object



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

def at(position)
  self[position]
end

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



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

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!



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

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

#capitalized?Boolean

Returns:

  • (Boolean)


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

def capitalized?
  capitalize == self
end

#classifyObject



78
79
80
# File 'lib/lite/ruby/string.rb', line 78

def classify
  dup.classify!
end

#classify!Object



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

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

#constantizeObject

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



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/lite/ruby/string.rb', line 89

def constantize
  names = split('::')
  Object.const_get(self) if names.empty?
  names.shift if names.size > 1 && names.first.empty?

  names.inject(Object) do |constant, name|
    return constant.const_get(name) if constant == Object

    candidate = constant.const_get(name)
    next candidate if constant.const_defined?(name, false)
    next candidate unless Object.const_defined?(name)

    constant = constant.ancestors.each_with_object(constant) do |ancestor, const|
      break const if ancestor == Object
      break ancestor if ancestor.const_defined?(name, false)
    end

    constant.const_get(name, false)
  end
end

#dasherizeObject

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



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

def dasherize
  dup.dasherize!
end

#dasherize!Object



116
117
118
# File 'lib/lite/ruby/string.rb', line 116

def dasherize!
  tr!('_', '-')
end

#deconstantizeObject



120
121
122
# File 'lib/lite/ruby/string.rb', line 120

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

#deconstantize!Object



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

def deconstantize!
  replace(deconstantize)
end

#dedupe(pattern) ⇒ Object



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

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

#dedupe!(pattern) ⇒ Object



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

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

#demodulizeObject



137
138
139
# File 'lib/lite/ruby/string.rb', line 137

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

#demodulize!Object



141
142
143
# File 'lib/lite/ruby/string.rb', line 141

def demodulize!
  replace(demodulize)
end

#domainObject



145
146
147
148
149
# File 'lib/lite/ruby/string.rb', line 145

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

  Regexp.last_match(1)
end

#downcase?Boolean

Returns:

  • (Boolean)


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

def downcase?
  downcase == self
end

#each_word(&block) ⇒ Object



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

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

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



174
175
176
177
178
179
180
181
# File 'lib/lite/ruby/string.rb', line 174

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

#encode_only(encoding, alt = '') ⇒ Object



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

def encode_only(encoding, alt = '')
  dup.encode_only!(encoding, alt)
end

#encode_only!(encoding, alt = '') ⇒ Object



163
164
165
166
167
168
169
170
171
172
# File 'lib/lite/ruby/string.rb', line 163

def encode_only!(encoding, alt = '')
  encoding_options = {
    invalid: :replace,
    undef: :replace,
    replace: alt,
    UNIVERSAL_NEWLINE_DECORATOR: true
  }

  encode!(Encoding.find(encoding), encoding_options)
end

#first(limit = 1) ⇒ Object



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

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

#format(*args) ⇒ Object



193
194
195
# File 'lib/lite/ruby/string.rb', line 193

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

#from(position) ⇒ Object



197
198
199
# File 'lib/lite/ruby/string.rb', line 197

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

#headerizeObject



201
202
203
# File 'lib/lite/ruby/string.rb', line 201

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

#headerize!Object



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

def headerize!
  replace(headerize)
end

#humanize(options = {}) ⇒ Object



209
210
211
# File 'lib/lite/ruby/string.rb', line 209

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

#humanize!(capitalize: true) ⇒ Object



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

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



222
223
224
# File 'lib/lite/ruby/string.rb', line 222

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

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



226
227
228
229
230
231
232
# File 'lib/lite/ruby/string.rb', line 226

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

#index_all(pattern) ⇒ Object



234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/lite/ruby/string.rb', line 234

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(options = {}) ⇒ Object Also known as: labelcase



248
249
250
# File 'lib/lite/ruby/string.rb', line 248

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

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



254
255
256
257
258
259
260
261
# File 'lib/lite/ruby/string.rb', line 254

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



265
266
267
268
269
270
271
272
273
# File 'lib/lite/ruby/string.rb', line 265

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

#lchomp(match) ⇒ Object



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

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

#lchomp!(match) ⇒ Object



279
280
281
282
283
284
# File 'lib/lite/ruby/string.rb', line 279

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

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

#methodizeObject



286
287
288
# File 'lib/lite/ruby/string.rb', line 286

def methodize
  dup.methodize!
end

#methodize!Object



290
291
292
293
294
295
296
# File 'lib/lite/ruby/string.rb', line 290

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)


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

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

#modulizeObject



298
299
300
# File 'lib/lite/ruby/string.rb', line 298

def modulize
  dup.modulize!
end

#modulize!Object



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

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



357
358
359
# File 'lib/lite/ruby/string.rb', line 357

def non_possessive
  dup.non_possessive!
end

#non_possessive!Object



361
362
363
364
365
# File 'lib/lite/ruby/string.rb', line 361

def non_possessive!
  return self unless possessive?

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

#ordinalObject



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

def ordinal
  to_i.ordinal
end

#ordinalizeObject



317
318
319
# File 'lib/lite/ruby/string.rb', line 317

def ordinalize
  to_i.ordinalize
end

#parameterize(separator: '-') ⇒ Object



321
322
323
# File 'lib/lite/ruby/string.rb', line 321

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

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



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

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

#pathizeObject



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

def pathize
  dup.pathize!
end

#pathize!Object



335
336
337
338
339
340
341
342
343
# File 'lib/lite/ruby/string.rb', line 335

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



345
346
347
# File 'lib/lite/ruby/string.rb', line 345

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

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



349
350
351
# File 'lib/lite/ruby/string.rb', line 349

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

#popObject



353
354
355
# File 'lib/lite/ruby/string.rb', line 353

def pop
  self[-1]
end

#possessiveObject



367
368
369
370
371
372
# File 'lib/lite/ruby/string.rb', line 367

def possessive
  return self if possessive?

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

#possessive!Object



374
375
376
# File 'lib/lite/ruby/string.rb', line 374

def possessive!
  replace(possessive)
end

#possessive?Boolean

Returns:

  • (Boolean)


378
379
380
# File 'lib/lite/ruby/string.rb', line 378

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

#push(string) ⇒ Object



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

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

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

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



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/lite/ruby/string.rb', line 387

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



426
427
428
# File 'lib/lite/ruby/string.rb', line 426

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

#remove(*patterns) ⇒ Object



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

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

#remove!(*patterns) ⇒ Object



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

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



440
441
442
# File 'lib/lite/ruby/string.rb', line 440

def remove_tags
  dup.remove_tags!
end

#remove_tags!Object



444
445
446
# File 'lib/lite/ruby/string.rb', line 444

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

#rotate(amount = 1) ⇒ Object



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

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

#rotate!(amount = 1) ⇒ Object



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

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

#sample(separator = ' ') ⇒ Object



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

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

#sample!(separator = ' ') ⇒ Object



461
462
463
# File 'lib/lite/ruby/string.rb', line 461

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

#shift(*patterns) ⇒ Object



465
466
467
# File 'lib/lite/ruby/string.rb', line 465

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

#shift!(*patterns) ⇒ Object



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

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

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

#shuffle(separator = '') ⇒ Object



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

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

#shuffle!(separator = '') ⇒ Object



479
480
481
# File 'lib/lite/ruby/string.rb', line 479

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

#sift(keep) ⇒ Object



483
484
485
486
487
488
489
490
491
492
# File 'lib/lite/ruby/string.rb', line 483

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



494
495
496
# File 'lib/lite/ruby/string.rb', line 494

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

#slugifyObject



498
499
500
# File 'lib/lite/ruby/string.rb', line 498

def slugify
  dup.slugify!
end

#slugify!Object



502
503
504
505
506
507
508
# File 'lib/lite/ruby/string.rb', line 502

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

#sortObject



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

def sort
  chars.sort.join
end

#sort!Object



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

def sort!
  replace(sort)
end

#squishObject



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

def squish
  dup.squish!
end

#squish!Object



514
515
516
517
# File 'lib/lite/ruby/string.rb', line 514

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

#titleizeObject Also known as: titlecase



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

def titleize
  dup.titleize!
end

#titleize!Object Also known as: titlecase!



533
534
535
536
537
# File 'lib/lite/ruby/string.rb', line 533

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

#to(position) ⇒ Object



541
542
543
# File 'lib/lite/ruby/string.rb', line 541

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

#transliterizeObject



545
546
547
# File 'lib/lite/ruby/string.rb', line 545

def transliterize
  dup.transliterize!
end

#transliterize!Object



549
550
551
# File 'lib/lite/ruby/string.rb', line 549

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

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



553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# File 'lib/lite/ruby/string.rb', line 553

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



569
570
571
572
573
574
575
# File 'lib/lite/ruby/string.rb', line 569

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



577
578
579
# File 'lib/lite/ruby/string.rb', line 577

def underscore
  dup.underscore!
end

#underscore!Object Also known as: snakecase!



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

def underscore!
  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



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

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

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



597
598
599
# File 'lib/lite/ruby/string.rb', line 597

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

#unquoteObject



614
615
616
# File 'lib/lite/ruby/string.rb', line 614

def unquote
  dup.unquote!
end

#unquote!Object



618
619
620
621
622
623
624
625
626
# File 'lib/lite/ruby/string.rb', line 618

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

  self
end

#unshift(*patterns) ⇒ Object



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

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

#unshift!(*patterns) ⇒ Object



610
611
612
# File 'lib/lite/ruby/string.rb', line 610

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

#upcase?Boolean

Returns:

  • (Boolean)


601
602
603
# File 'lib/lite/ruby/string.rb', line 601

def upcase?
  upcase == self
end

#variablizeObject



641
642
643
# File 'lib/lite/ruby/string.rb', line 641

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

#variablize!Object



645
646
647
# File 'lib/lite/ruby/string.rb', line 645

def variablize!
  replace(variablize)
end

#wordsObject



628
629
630
# File 'lib/lite/ruby/string.rb', line 628

def words
  split(/\s+/)
end

#words_without_punctuationObject



632
633
634
635
636
637
638
639
# File 'lib/lite/ruby/string.rb', line 632

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