Class: String

Inherits:
Object show all
Defined in:
lib/epitools/minimal.rb,
lib/epitools/core_ext/string.rb,
lib/epitools/core_ext/truthiness.rb

Constant Summary collapse

LOWERCASE_WORDS =

For `titlecase`

Set.new %w[of to or the and an a at is for from in]
STOP_WORDS =

For `words_without_stopwords`

%w[a cannot into our thus about co is ours to above could it ourselves together across down its out too after during itself over toward afterwards each last own towards again eg latter per under against either latterly perhaps until all else least rather up almost elsewhere less same upon alone enough ltd seem us along etc many seemed very already even may seeming via also ever me seems was although every meanwhile several we always everyone might she well among everything more should were amongst everywhere moreover since what an except most so whatever and few mostly some when another first much somehow whence any for must someone whenever anyhow former my something where anyone formerly myself sometime whereafter anything from namely sometimes whereas anywhere further neither somewhere whereby are had never still wherein around has nevertheless such whereupon as have next than wherever at he no that whether be hence nobody the whither became her none their which because here noone them while become hereafter nor themselves who becomes hereby not then whoever becoming herein nothing thence whole been hereupon now there whom before hers nowhere thereafter whose beforehand herself of thereby why behind him off therefore will being himself often therein with below his on thereupon within beside how once these without besides however one they would between i only this yet beyond ie onto those you both if or though your but in other through yours by inc others throughout yourself can indeed otherwise thru yourselves]
COLOR_REGEXP =

A Regexp to recognize ANSI escape sequences

/\e\[.*?(\d)*[mA-Z]/
BASE_DIGITS =

Cached constants for base conversion.

Integer::BASE_DIGITS.map.with_index.to_h

Instance Method Summary collapse

Instance Method Details

#amount(n) ⇒ Object

Convert this string into a string describing this many of the string. (Note: Doesn't know anything about proper grammar.)

Example:

"cookie".amount(0)    #=> "0 cookies"
"shirt".amount(17)    #=> "17 shirts"
"dollar".amount(-10)  #=> "-10 dollars"
"love".amount(1)      #=> "1 love"

473
474
475
476
477
478
479
480
481
482
# File 'lib/epitools/core_ext/string.rb', line 473

def amount(n)
  case n
  when 0
    "0 #{self}s"
  when 1, -1
    "#{n} #{self}"
  else
    "#{n} #{self}s"
  end
end

#any?Boolean Also known as: present?

Is there anything in the string? (ignoring whitespace/newlines)


133
134
135
# File 'lib/epitools/core_ext/truthiness.rb', line 133

def any?
  not blank?
end

#blank?Boolean

'true' if the string's length is 0 (after whitespace has been stripped from the ends)


126
127
128
# File 'lib/epitools/core_ext/truthiness.rb', line 126

def blank?
  strip.size == 0
end

#contains_color?Boolean Also known as: contains_colors?, contains_ansi?

This string contains ANSI (VT100) control codes


83
84
85
# File 'lib/epitools/core_ext/string.rb', line 83

def contains_color?
  self[COLOR_REGEXP]
end

#deflate(level = nil) ⇒ Object

deflate the string


415
416
417
# File 'lib/epitools/core_ext/string.rb', line 415

def deflate(level=nil)
  Zlib::Deflate.deflate(self, level)
end

#dewhitespaceObject

Remove redundant whitespace AND newlines.


48
49
50
# File 'lib/epitools/core_ext/string.rb', line 48

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

#each_chompedObject Also known as: chomped_lines, chomp_lines

Like #each_line, but removes trailing n


111
112
113
# File 'lib/epitools/core_ext/string.rb', line 111

def each_chomped
  each_line { |line| yield line.chomp }
end

#each_slice(slice_width, &block) ⇒ Object

Iterate over slices of the string of size `slice_width`.


255
256
257
258
259
260
261
262
# File 'lib/epitools/core_ext/string.rb', line 255

def each_slice(slice_width, &block)
  max = size
  p = 0
  while p < max
    yield self[p...p+slice_width]
    p += slice_width
  end
end

#endswith?(substring) ⇒ Boolean Also known as: endswith

`true` if this string ends with the substring


436
437
438
# File 'lib/epitools/core_ext/string.rb', line 436

def endswith?(substring)
  self[-substring.size..-1] == substring
end

#float?Boolean

Could this string be cast to an float?


112
113
114
# File 'lib/epitools/core_ext/truthiness.rb', line 112

def float?
  !!strip.match(/^-?\d+\.\d+$/)
end

#from_base(base = 10) ⇒ Object

Convert a string encoded in some base <= 64 into an integer. (See Integer#to_base for more info.)


329
330
331
332
333
334
335
336
# File 'lib/epitools/core_ext/string.rb', line 329

def from_base(base=10)
  n = 0
  chars.reverse_each.with_index do |c, power|
    value = BASE_DIGITS[c]
    n += (base**power) * value
  end
  n
end

#from_base62Object


338
339
340
# File 'lib/epitools/core_ext/string.rb', line 338

def from_base62
  from_base(62)
end

#from_base64Object Also known as: decode64

Decode a mime64/base64 encoded string


353
354
355
# File 'lib/epitools/core_ext/string.rb', line 353

def from_base64
  unpack("m").first
end

#from_bencodeObject

Convert Python serialized bencoded (pickled) objects to Ruby Objects


370
371
372
# File 'lib/epitools/core_ext/string.rb', line 370

def from_bencode
  BEncode.load(self)
end

#from_hmsObject

Converts time duration strings (mm:ss, mm:ss.dd, hh:mm:ss, or dd:hh:mm:ss) to seconds. (The reverse of Integer#to_hms)


488
489
490
491
492
493
494
495
496
# File 'lib/epitools/core_ext/string.rb', line 488

def from_hms
  nums = split(':')

  nums[-1] = nums[-1].to_f if nums[-1] =~ /\d+\.\d+/ # convert fractional seconds to a float
  nums.map! { |n| n.is_a?(String) ? n.to_i : n } # convert the rest to integers

  nums_and_units = nums.reverse.zip %w[seconds minutes hours days]
  nums_and_units.map { |num, units| num.send(units) }.sum
end

#from_jsonObject

Parse this string as JSON


444
445
446
# File 'lib/epitools/core_ext/string.rb', line 444

def from_json
  JSON.parse(self)
end

#from_yamlObject

Parse this string as YAML


451
452
453
# File 'lib/epitools/core_ext/string.rb', line 451

def from_yaml
  YAML.load(self)
end

#gunzipObject

gunzip the string


407
408
409
410
# File 'lib/epitools/core_ext/string.rb', line 407

def gunzip
  data = StringIO.new(self)
  Zlib::GzipReader.new(data).read
end

#gzip(level = nil) ⇒ Object

gzip the string


398
399
400
401
402
# File 'lib/epitools/core_ext/string.rb', line 398

def gzip(level=nil)
  zipped = StringIO.new
  Zlib::GzipWriter.wrap(zipped, level) { |io| io.write(self) }
  zipped.string
end

#hexdumpObject

Print a hexdump of the string to STDOUT (coloured, if the terminal supports it)


501
502
503
# File 'lib/epitools/core_ext/string.rb', line 501

def hexdump
  Hex.dump(self)
end

#indent(prefix = " ") ⇒ Object

Indent all the lines, if “prefix” is a string, prepend that string to each lien. If it's an integer, prepend that many spaces.


152
153
154
155
156
157
158
159
160
# File 'lib/epitools/core_ext/string.rb', line 152

def indent(prefix="  ")
  prefix = (" " * prefix) if prefix.is_an? Integer

  if block_given?
    lines.each { |line| yield prefix + line }
  else
    lines.map { |line| prefix + line }.join('')
  end
end

#inflateObject

inflate the string


422
423
424
# File 'lib/epitools/core_ext/string.rb', line 422

def inflate
  Zlib::Inflate.inflate(self)
end

#integer?Boolean

Could this string be cast to an integer?


105
106
107
# File 'lib/epitools/core_ext/truthiness.rb', line 105

def integer?
  !!strip.match(/^-?\d+$/)
end

#md5Object

MD5 the string


377
378
379
# File 'lib/epitools/core_ext/string.rb', line 377

def md5
  Digest::MD5.hexdigest self
end

#nice_html(indent = 2) ⇒ Object Also known as: nicehtml, indent_html

Use Nokogiri to parse this string as HTML, and return an indented version


165
166
167
# File 'lib/epitools/core_ext/string.rb', line 165

def nice_html(indent=2)
  Nokogiri::HTML.fragment(self).to_xhtml(indent: indent)
end

#nice_linesObject Also known as: nicelines, clean_lines

Like #each_line, but skips empty lines and removes n's.


100
101
102
103
# File 'lib/epitools/core_ext/string.rb', line 100

def nice_lines
  # note: $/ is the platform's newline separator
  split($/).select{|l| not l.blank? }
end

#number?Boolean

Could this string be cast to an number?


119
120
121
# File 'lib/epitools/core_ext/truthiness.rb', line 119

def number?
  !!strip.match(/^-?\d\.?\d*$/)
end

#rot13Object

The Infamous Caesar-Cipher. Unbreakable to this day.


268
269
270
# File 'lib/epitools/core_ext/string.rb', line 268

def rot13
  tr('n-za-mN-ZA-M', 'a-zA-Z')
end

#sentencesObject


239
240
241
# File 'lib/epitools/core_ext/string.rb', line 239

def sentences
  split_after(/[\.\!\?]+/).lazy.map {|s| s.strip.gsub(/\s+/, " ") }
end

#sha1Object

SHA1 the string


384
385
386
# File 'lib/epitools/core_ext/string.rb', line 384

def sha1
  Digest::SHA1.hexdigest self
end

#sha256Object

SHA256 the string


391
392
393
# File 'lib/epitools/core_ext/string.rb', line 391

def sha256
  Digest::SHA256.hexdigest self
end

#shellescapeObject

Escape shell characters (globs, quotes, parens, etc.)


27
28
29
# File 'lib/epitools/core_ext/string.rb', line 27

def shellescape
  Shellwords.escape(self)
end

#smashObject

Smash together all the characters in a string (removing whitespace)


41
42
43
# File 'lib/epitools/core_ext/string.rb', line 41

def smash
  downcase.scan(/\w+/).join
end

#split_after(boundary) ⇒ Object


140
141
142
# File 'lib/epitools/core_ext/string.rb', line 140

def split_after(boundary)
  split_at(boundary, include_boundary: true)
end

#split_at(boundary, options = {}) ⇒ Object


118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/epitools/core_ext/string.rb', line 118

def split_at(boundary, options={})
  include_boundary = options[:include_boundary] || false

  boundary = Regexp.new(Regexp.escape(boundary)) if boundary.is_a?(String)
  s        = StringScanner.new(self)

  Enumerator.new do |yielder|
    loop do
      if match = s.scan_until(boundary)
        if include_boundary
          yielder << match
        else
          yielder << match[0..-(s.matched_size+1)]
        end
      else
        yielder << s.rest if s.rest?
        break
      end
    end
  end
end

#split_before(boundary) ⇒ Object


144
145
146
# File 'lib/epitools/core_ext/string.rb', line 144

def split_before(boundary)
  raise "Why would you want this? Sorry, unimplemented. Send patches."
end

#startswith?(substring) ⇒ Boolean Also known as: startswith

`true` if this string starts with the substring


428
429
430
# File 'lib/epitools/core_ext/string.rb', line 428

def startswith?(substring)
  self[0...substring.size] == substring
end

#strip_colorObject Also known as: strip_ansi

Remove ANSI color codes.


92
93
94
# File 'lib/epitools/core_ext/string.rb', line 92

def strip_color
  gsub(COLOR_REGEXP, '')
end

#tightenObject

Remove redundant whitespaces (not including newlines).


34
35
36
# File 'lib/epitools/core_ext/string.rb', line 34

def tighten
  gsub(/[\t ]+/,' ').strip
end

#titlecaseObject

Return a new string converted to “Title Case” (first letter of each word capitalized)


55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/epitools/core_ext/string.rb', line 55

def titlecase
  first = true
  words = downcase.split(/(?<!\w')\b/)

  words.map.with_index do |word,i|
    if LOWERCASE_WORDS.include?(word) and i > 0 # leave LOWERCASE_WORDS lowercase, unless it's the first word.
      word
    else
      word.gsub(/^\w/) { |c| c.upcase } # capitalize first letter
    end
  end.join('')
end

#titlecase!Object

Convert string to “Title Case” (first letter of each word capitalized)


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

def titlecase!
  replace(titlecase)
end

#to_base62Object

Convert a string (encoded in base16 “hex” – for example, an MD5 or SHA1 hash) into “base62” format. (See Integer#to_base62 for more info.)


346
347
348
# File 'lib/epitools/core_ext/string.rb', line 346

def to_base62
  to_i(16).to_base62
end

#to_base64Object Also known as: base64, encode64

Encode into a mime64/base64 string


361
362
363
# File 'lib/epitools/core_ext/string.rb', line 361

def to_base64
  [self].pack("m")
end

#to_i_from_bytes(big_endian = false) ⇒ Object

Raw bytes to an integer (as big as necessary)


315
316
317
318
# File 'lib/epitools/core_ext/string.rb', line 315

def to_i_from_bytes(big_endian=false)
  bs = big_endian ? bytes.reverse_each : bytes.each
  bs.with_index.inject(0) { |sum,(b,i)| (b << (8*i)) + sum }
end

#to_paramsObject

Convert a query string to a hash of params


297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/epitools/core_ext/string.rb', line 297

def to_params
  params = {}

  split(/[&;]/).each do |pairs|
    key, value = pairs.split('=',2).collect { |v| CGI.unescape(v) }

    if key and value
      params[key] ||= []
      params[key] << value
    end
  end

  params.map_values { |v| v.size > 1 ? v : v.first }
end

#to_PathObject Also known as: to_P

Convert the string to a Path object (for representing files/directories).


266
267
268
# File 'lib/epitools/minimal.rb', line 266

def to_Path
  Path[self]
end

#to_proc(&block) ⇒ Object

String#to_proc

See: weblog.raganwald.com/2007/10/stringtoproc.html

Ported from the String Lambdas in Oliver Steele's Functional Javascript osteele.com/sources/javascript/functional/

This work is licensed under the MIT License:

© 2007 Reginald Braithwaite Portions Copyright © 2006 Oliver Steele

## Basic Usage

'x+1’.to_proc;

'x+2*y'.to_proc[2, 3];

or (more usefully) later:

square = 'x*x'.to_proc; square(3);

square(4);

## Explicit parameters

If the string contains a ->, this separates the parameters from the body.

'x y -> x+2*y'.to_proc[2, 3];

'y x -> x+2*y'.to_proc[2, 3];

Otherwise, if the string contains a _, it’s a unary function and _ is name of the parameter:

'_+1’.to_proc;

'_*_’.to_proc;

## Implicit parameters

If the string doesn’t specify explicit parameters, they are implicit.

If the string starts with an operator or relation besides -, or ends with an operator or relation, then its implicit arguments are placed at the beginning and/or end:

'*2’.to_proc;

'/2’.to_proc;

'2/‘.to_proc;

'/'.to_proc[2, 4];

’.’ counts as a right operator:

'.abs’.to_proc;

Otherwise, the variables in the string, in order of occurrence, are its parameters.

'x+1’.to_proc;

'x*x’.to_proc;

'x + 2*y'.to_proc[1, 2];

'y + 2*x'.to_proc[1, 2];

## Chaining

Chain -> to create curried functions.

'x y -> x+y'.to_proc[2, 3];

'x -> y -> x+y’.to_proc[3];

plus_two = 'x -> y -> x+y’.to_proc; plus_two

Using String#to_proc in Idiomatic Ruby

Ruby on Rails popularized Symbol#to_proc, so much so that it will be part of Ruby 1.9.

If you like:

%w[dsf fgdg fg].map(&:capitalize)

then %w[dsf fgdg fg].map(&'.capitalize') isn’t much of an improvement.

But what about doubling every value in a list:

(1..5).map &'*2'

Or folding a list:

(1..5).inject &'+'

Or having fun with factorial:

factorial = “(1.._).inject &'*'”.to_proc factorial

LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/epitools/core_ext/string.rb', line 638

def to_proc &block
  params = []
  expr = self
  sections = expr.split(/\s*->\s*/m)
  if sections.length > 1 then
      eval_block(sections.reverse!.inject { |e, p| "(Proc.new { |#{p.split(/\s/).join(', ')}| #{e} })" }, block)
  elsif expr.match(/\b_\b/)
      eval_block("Proc.new { |_| #{expr} }", block)
  else
      leftSection = expr.match(/^\s*(?:[+*\/%&|\^\.=<>\[]|!=)/m)
      rightSection = expr.match(/[+\-*\/%&|\^\.=<>!]\s*$/m)
      if leftSection || rightSection then
          if (leftSection) then
              params.push('$left')
              expr = '$left' + expr
          end
          if (rightSection) then
              params.push('$right')
              expr = expr + '$right'
          end
      else
          self.gsub(
              /(?:\b[A-Z]|\.[a-zA-Z_$])[a-zA-Z_$\d]*|[a-zA-Z_$][a-zA-Z_$\d]*:|self|arguments|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/, ''
          ).scan(
            /([a-z_$][a-z_$\d]*)/i
          ) do |v|
            params.push(v) unless params.include?(v)
          end
      end
      eval_block("Proc.new { |#{params.join(', ')}| #{expr} }", block)
  end
end

#to_unixObject

Convert rn to n


20
21
22
# File 'lib/epitools/core_ext/string.rb', line 20

def to_unix
  gsub("\r\n", "\n")
end

#to_uriObject Also known as: to_URI

URI.parse the string and return an URI object


289
290
291
# File 'lib/epitools/core_ext/string.rb', line 289

def to_uri
  URI.parse self
end

#truthy?Boolean

Does this string contain something that means roughly “true”?


141
142
143
144
145
146
147
148
# File 'lib/epitools/core_ext/truthiness.rb', line 141

def truthy?
  case strip.downcase
  when "1", "true", "yes", "on", "enabled", "affirmative"
    true
  else
    false
  end
end

#unmarshalObject Also known as: from_marshal

Unmarshal the string (transform it into Ruby datatypes).


458
459
460
# File 'lib/epitools/core_ext/string.rb', line 458

def unmarshal
  Marshal.restore self
end

#urldecodeObject

Convert an URI's %XXes into regular characters.


282
283
284
# File 'lib/epitools/core_ext/string.rb', line 282

def urldecode
  URI.unescape(self)
end

#urlencodeObject

Convert non-URI characters into %XXes.


275
276
277
# File 'lib/epitools/core_ext/string.rb', line 275

def urlencode
  URI.escape(self)
end

#wordsObject


243
244
245
# File 'lib/epitools/core_ext/string.rb', line 243

def words
  scan /[[:alnum:]]+/
end

#words_without_stopwordsObject Also known as: without_stopwords


247
248
249
# File 'lib/epitools/core_ext/string.rb', line 247

def words_without_stopwords
  downcase.words - STOP_WORDS
end

#wrap(width = nil) ⇒ Object Also known as: word_wrap

Word-wrap the string so each line is at most `width` wide. Returns a string, or, if a block is given, yields each word-wrapped line to the block.

If `width` is nil, find the current width of the terminal and use that. If `width` is negative, subtract `width` from the terminal's current width.


179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/epitools/core_ext/string.rb', line 179

def wrap(width=nil)
  if width.nil? or width < 0
    term_width, _ = Term.size

    if width and width < 0
      width = (term_width - 1) + width
    else
      width = term_width - 1
    end
  end

  return self if size <= width

  strings   = []
  start_pos = 0
  end_pos   = width

  loop do
    split_pos = rindex(/\s/, end_pos) || end_pos

    strings << self[start_pos...split_pos]

    start_pos = index(/\S/, split_pos)
    break if start_pos == nil
    end_pos   = start_pos + width

    if end_pos > size
      strings << self[start_pos..-1]
      break
    end
  end

  if block_given?
    strings.each { |s| yield s }
  else
    strings.join("\n")
  end
end

#wrap_and_indent(prefix, width = nil) ⇒ Object Also known as: wrapdent

Wrap all lines at window size, and indent


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

def wrap_and_indent(prefix, width=nil)
  prefix = " "*prefix if prefix.is_a? Numeric

  prefix_size = prefix.strip_color.size

  if width
    width = width - prefix_size
  else
    width = -prefix_size
  end

  wrap(width).each_line.map { |line| prefix + line }.join
end