class String
Constants
- TRANSLITERATIONS
Public Instance Methods
acronym()
click to toggle source
# File lib/lite/ruby/string.rb, line 11 def acronym gsub(/(([a-zA-Z0-9])([a-zA-Z0-9])*)./, '\\2') || self end
acronym!()
click to toggle source
# File lib/lite/ruby/string.rb, line 15 def acronym! replace(acronym) end
any?(*keys)
click to toggle source
# File lib/lite/ruby/string.rb, line 19 def any?(*keys) keys.any? { |key| include?(key) } end
at(position)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 5 def at(position) self[position] end
camelize(first_letter = :upper)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 9 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 } else modulize end end
Also aliased as: camelcase
camelize!(first_letter = :upper)
click to toggle source
# File lib/lite/ruby/string.rb, line 23 def camelize!(first_letter = :upper) replace(camelize(first_letter)) end
Also aliased as: camelcase!
capitalized?()
click to toggle source
# File lib/lite/ruby/string.rb, line 27 def capitalized? capitalize == self end
classify()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 17 def classify str = dup str.sub!(/.*\./, '') str.camelize! str || self end
classify!()
click to toggle source
# File lib/lite/ruby/string.rb, line 31 def classify! replace(classify) end
constantize()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 24 def constantize Object.const_get(camelize) end
dasherize()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 28 def dasherize underscore.tr('_', '-') end
dasherize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 35 def dasherize! replace(dasherize) end
deconstantize()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 32 def deconstantize [0, rindex('::') || 0] end
deconstantize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 39 def deconstantize! replace(deconstantize) end
dedupe(pattern)
click to toggle source
# File lib/lite/ruby/string.rb, line 43 def dedupe(pattern) dup.dedupe!(pattern) end
dedupe!(pattern)
click to toggle source
# File lib/lite/ruby/string.rb, line 47 def dedupe!(pattern) pattern.each_char { |char| gsub!(/#{Regexp.escape(char)}{2,}/, char) } self end
demodulize()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 36 def demodulize gsub(/^.*::/, '') end
demodulize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 52 def demodulize! replace(demodulize) end
domain()
click to toggle source
# File lib/lite/ruby/string.rb, line 56 def domain return self unless self =~ %r{^(?:\w+://)?([^/?]+)(?:/|\?|$)} Regexp.last_match(1) end
downcase?()
click to toggle source
# File lib/lite/ruby/string.rb, line 62 def downcase? downcase == self end
each_word(&block)
click to toggle source
# File lib/lite/ruby/string.rb, line 66 def each_word(&block) words.each(&block) end
ellipsize(ellipsize_at, options = {})
click to toggle source
# File lib/lite/ruby/string.rb, line 70 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)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 40 def first(limit = 1) if limit.zero? '' elsif limit >= length self else to(limit - 1) end end
format(*args)
click to toggle source
Calls superclass method
# File lib/lite/ruby/string.rb, line 79 def format(*args) super(self, *args.flatten) end
from(position)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 50 def from(position) self[position..-1] end
headerize()
click to toggle source
# File lib/lite/ruby/string.rb, line 83 def headerize squish.each_word(&:capitalize!).join(' ') end
headerize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 87 def headerize! replace(headerize) end
humanize(capitalize: true)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 54 def humanize(capitalize: true) str = dup str.underscore! str.delete_suffix!('_id') str.tr!('_', ' ') str.squish! str.gsub!(/([a-z\d]*)/i, &:downcase) str.gsub!(/\A\w/) { |s| capitalize ? s.upcase : s } str || self end
humanize!(capitalize: true)
click to toggle source
# File lib/lite/ruby/string.rb, line 91 def humanize!(capitalize: true) replace(humanize(capitalize: capitalize)) end
indent(amount, seperator = ' ')
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 65 def indent(amount, seperator = ' ') dup.indent!(amount, seperator) end
indent!(amount, seperator = ' ')
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 69 def indent!(amount, seperator = ' ') if amount >= 0 gsub!(/^/, seperator * amount) else gsub!(/^#{Regexp.escape(seperator)}{0,#{-amount}}/, '') end end
index_all(pattern)
click to toggle source
# File lib/lite/ruby/string.rb, line 95 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)
click to toggle source
# File lib/lite/ruby/string.rb, line 109 def labelize(capitalize: true) dup.labelize!(capitalize: capitalize) end
Also aliased as: labelcase
labelize!(capitalize: true)
click to toggle source
# File lib/lite/ruby/string.rb, line 113 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
Also aliased as: labelcase!
last(limit = 1)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 77 def last(limit = 1) if limit.zero? '' elsif limit >= length self else from(-limit) end end
lchomp(match)
click to toggle source
# File lib/lite/ruby/string.rb, line 122 def lchomp(match) dup.lchomp!(match) end
lchomp!(match)
click to toggle source
# File lib/lite/ruby/string.rb, line 126 def lchomp!(match) return self unless index(match) self[0...match.size] = '' self end
methodize()
click to toggle source
# File lib/lite/ruby/string.rb, line 133 def methodize dup.methodize! end
methodize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 137 def methodize! gsub!(/([A-Z]+)([A-Z])/, '\1_\2') gsub!(/([a-z])([A-Z])/, '\1_\2') gsub!('/', '__') gsub!('::', '__') downcase! || self end
mixedcase?()
click to toggle source
# File lib/lite/ruby/string.rb, line 156 def mixedcase? !upcase? && !downcase? end
modulize()
click to toggle source
# File lib/lite/ruby/string.rb, line 145 def modulize dup.modulize! end
modulize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 149 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_possessive()
click to toggle source
# File lib/lite/ruby/string.rb, line 160 def non_possessive dup.non_possessive! end
non_possessive!()
click to toggle source
# File lib/lite/ruby/string.rb, line 164 def non_possessive! return self unless possessive? chomp!("'s") || chomp!("'") || self end
ordinal()
click to toggle source
# File lib/lite/ruby/string.rb, line 170 def ordinal to_i.ordinal end
ordinalize()
click to toggle source
# File lib/lite/ruby/string.rb, line 174 def ordinalize to_i.ordinalize end
parameterize(separator: '-')
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 87 def parameterize(separator: '-') str = dup str.underscore! str.gsub!(/\s+/, separator) str.downcase! str || self end
parameterize!(separator: '-')
click to toggle source
# File lib/lite/ruby/string.rb, line 178 def parameterize!(separator: '-') replace(parameterize(separator: separator)) end
pathize()
click to toggle source
# File lib/lite/ruby/string.rb, line 182 def pathize dup.pathize! end
pathize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 186 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 = '^--^--^')
click to toggle source
# File lib/lite/ruby/string.rb, line 196 def pollute(delimiter = '^--^--^') chars.map { |chr| "#{chr}#{delimiter}" }.join end
pollute!(delimiter = '^--^--^')
click to toggle source
# File lib/lite/ruby/string.rb, line 200 def pollute!(delimiter = '^--^--^') replace(pollute(delimiter)) end
pop()
click to toggle source
# File lib/lite/ruby/string.rb, line 204 def pop self[-1] end
possessive()
click to toggle source
# File lib/lite/ruby/string.rb, line 208 def possessive return self if possessive? possession = end_with?('s') ? "'" : "'s" "#{self}#{possession}" end
possessive!()
click to toggle source
# File lib/lite/ruby/string.rb, line 215 def possessive! replace(possessive) end
possessive?()
click to toggle source
# File lib/lite/ruby/string.rb, line 219 def possessive? %w['s s'].any? { |pos| end_with?(pos) } end
push(string)
click to toggle source
# File lib/lite/ruby/string.rb, line 223 def push(string) replace(concat(string)) end
quote(type = :double, amount = nil)
click to toggle source
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
# File lib/lite/ruby/string.rb, line 228 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)
click to toggle source
rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
# File lib/lite/ruby/string.rb, line 267 def quote!(type = :double, amount = nil) replace(quote(type, amount)) end
remove(*patterns)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 95 def remove(*patterns) dup.remove!(*patterns) end
remove!(*patterns)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 99 def remove!(*patterns) patterns.each_with_object(self) do |pat, str| pat.is_a?(Range) ? str.slice!(pat) : str.gsub!(pat, '') end end
rotate(amount = 1)
click to toggle source
# File lib/lite/ruby/string.rb, line 279 def rotate(amount = 1) dup.rotate!(amount) end
rotate!(amount = 1)
click to toggle source
# File lib/lite/ruby/string.rb, line 283 def rotate!(amount = 1) amount += size if amount.negative? slice!(amount, size - amount) + slice!(0, amount) end
safe_encode(target_encoding, replacement = '')
click to toggle source
rubocop:disable Metrics/MethodLength
# File lib/lite/ruby/string.rb, line 289 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 = '')
click to toggle source
rubocop:enable Metrics/MethodLength
# File lib/lite/ruby/string.rb, line 304 def safe_encode!(target_encoding, replacement = '') replace(safe_encode(target_encoding, replacement)) end
sample(separator = ' ')
click to toggle source
# File lib/lite/ruby/string.rb, line 308 def sample(separator = ' ') split(separator).sample end
sample!(separator = ' ')
click to toggle source
# File lib/lite/ruby/string.rb, line 312 def sample!(separator = ' ') replace(sample(separator)) end
shift(*patterns)
click to toggle source
# File lib/lite/ruby/string.rb, line 316 def shift(*patterns) dup.shift!(*patterns) end
shift!(*patterns)
click to toggle source
# File lib/lite/ruby/string.rb, line 320 def shift!(*patterns) return self[0] if patterns.empty? patterns.each_with_object(self) { |pat, str| str.sub!(pat, '') } end
shuffle(separator = '')
click to toggle source
# File lib/lite/ruby/string.rb, line 326 def shuffle(separator = '') split(separator).shuffle.join end
shuffle!(separator = '')
click to toggle source
# File lib/lite/ruby/string.rb, line 330 def shuffle!(separator = '') replace(shuffle(separator)) end
sift(keep)
click to toggle source
# File lib/lite/ruby/string.rb, line 334 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)
click to toggle source
# File lib/lite/ruby/string.rb, line 345 def sift!(keep) replace(sift(keep)) end
slugify()
click to toggle source
# File lib/lite/ruby/string.rb, line 349 def slugify dup.slugify! end
slugify!()
click to toggle source
# File lib/lite/ruby/string.rb, line 353 def slugify! gsub!(/[^\x00-\x7F]+/, '') gsub!(/[^\w \-]+/i, '') gsub!(/[ \-]+/i, '-') gsub!(/^-|-$/i, '') downcase! || self end
sort()
click to toggle source
# File lib/lite/ruby/string.rb, line 361 def sort chars.sort.join end
sort!()
click to toggle source
# File lib/lite/ruby/string.rb, line 365 def sort! replace(sort) end
squish()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 105 def squish dup.squish! end
squish!()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 109 def squish! strip! gsub!(/\s+/, ' ') || self end
titleize()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 114 def titleize str = dup str.underscore! str.humanize! str.gsub!(/\b(?<!['’`])[a-z]/) { $&.capitalize } str || self end
Also aliased as: titlecase
titleize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 377 def titleize! replace(titleize) end
Also aliased as: titlecase!
to(position)
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 122 def to(position) self[0..position] end
to_time(form = :local)
click to toggle source
rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity rubocop:disable Metrics/MethodLength, Metrics/PerceivedComplexity
# File lib/lite/ruby/safe/string.rb, line 128 def to_time(form = :local) parts = Date.parse(self, false) used_keys = %i[year mon mday hour min sec sec_fraction offset] return if (parts.keys & used_keys).empty? now = Time.now time = Time.new( parts[:year] || now.year, parts[:mon] || now.month, parts[:mday] || now.day, parts[:hour] || 0, parts[:min] || 0, (parts[:sec] || 0) + (parts[:sec_fraction] || 0), parts[:offset] || (form == :utc ? 0 : nil) ) form == :utc ? time.utc : time.to_time end
Also aliased as: to_t
transliterize()
click to toggle source
# File lib/lite/ruby/string.rb, line 369 def transliterize TRANSLITERATIONS.each_with_object(dup) { |(k, v), s| s.gsub!(k, v) } end
transliterize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 373 def transliterize! replace(transliterize) end
truncate(truncate_at, options = {})
click to toggle source
rubocop:enable Metrics/MethodLength, Metrics/PerceivedComplexity rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity
# File lib/lite/ruby/safe/string.rb, line 149 def truncate(truncate_at, options = {}) return self unless length > truncate_at omission = options[:omission] || '...' seperator = options[:separator] size_with_room_for_omission = truncate_at - omission.length stop = rindex(seperator || '', size_with_room_for_omission) if seperator "#{self[0, stop || size_with_room_for_omission]}#{omission}" end
truncate_words(words_count, options = {})
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 159 def truncate_words(words_count, options = {}) sep = options[:separator] || /\s+/ sep = Regexp.escape(sep.to_s) unless sep.is_a?(Regexp) return dup unless self =~ /\A((?>.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m $1 + (options[:omission] || '...') end
underscore()
click to toggle source
# File lib/lite/ruby/safe/string.rb, line 167 def underscore str = dup str.camelize! str.gsub!(/::/, '/') str.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2') str.gsub!(/([a-z\d])([A-Z])/, '\1_\2') str.tr!('-', '_') str.downcase! str || self end
Also aliased as: snakecase
underscore!()
click to toggle source
# File lib/lite/ruby/string.rb, line 385 def underscore! replace(underscore) end
Also aliased as: snakecase!
unpollute(delimiter = '^--^--^')
click to toggle source
# File lib/lite/ruby/string.rb, line 389 def unpollute(delimiter = '^--^--^') dup.unpollute!(delimiter) end
unpollute!(delimiter = '^--^--^')
click to toggle source
# File lib/lite/ruby/string.rb, line 393 def unpollute!(delimiter = '^--^--^') gsub!(delimiter, '') || self end
unquote()
click to toggle source
# File lib/lite/ruby/string.rb, line 397 def unquote dup.unquote! end
unquote!()
click to toggle source
# File lib/lite/ruby/string.rb, line 401 def unquote! [0, -1].each do |i| case self[i, 1] when "'", '"', '`' then self[i] = '' end end self end
unshift(*patterns)
click to toggle source
# File lib/lite/ruby/string.rb, line 411 def unshift(*patterns) patterns.each_with_object('') { |pat, str| str << pat } .concat(self) end
unshift!(*patterns)
click to toggle source
# File lib/lite/ruby/string.rb, line 416 def unshift!(*patterns) replace(unshift(*patterns)) end
upcase?()
click to toggle source
# File lib/lite/ruby/string.rb, line 381 def upcase? upcase == self end
variablize()
click to toggle source
# File lib/lite/ruby/string.rb, line 433 def variablize "@#{gsub(/\W/, '_')}" end
variablize!()
click to toggle source
# File lib/lite/ruby/string.rb, line 437 def variablize! replace(variablize) end
words()
click to toggle source
# File lib/lite/ruby/string.rb, line 420 def words split(/\s+/) end
words_without_punctuation()
click to toggle source
# File lib/lite/ruby/string.rb, line 424 def words_without_punctuation str = dup str.gsub!(%r{[.?¿¡…!,::;—"。?!、‘“”„«»〈〉《》,/\[\]]}, ' ') str.gsub!('- ', ' ') str.squeeze!(' ') str.strip! str.words end