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"

459
460
461
462
463
464
465
466
467
468
# File 'lib/epitools/core_ext/string.rb', line 459

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


76
77
78
# File 'lib/epitools/core_ext/string.rb', line 76

def contains_color?
  self[COLOR_REGEXP]
end

#deflate(level = nil) ⇒ Object

deflate the string


401
402
403
# File 'lib/epitools/core_ext/string.rb', line 401

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

#dewhitespaceObject

Remove redundant whitespace AND newlines.


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

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

#each_chompedObject Also known as: chomped_lines, chomp_lines

Like #each_line, but removes trailing n


104
105
106
# File 'lib/epitools/core_ext/string.rb', line 104

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`.


248
249
250
251
252
253
254
255
# File 'lib/epitools/core_ext/string.rb', line 248

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


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

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.)


322
323
324
325
326
327
328
329
# File 'lib/epitools/core_ext/string.rb', line 322

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


331
332
333
# File 'lib/epitools/core_ext/string.rb', line 331

def from_base62
  from_base(62)
end

#from_base64Object Also known as: decode64

Decode a mime64/base64 encoded string


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

def from_base64
  unpack("m").first
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)


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

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


430
431
432
# File 'lib/epitools/core_ext/string.rb', line 430

def from_json
  JSON.parse(self)
end

#from_yamlObject

Parse this string as YAML


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

def from_yaml
  YAML.load(self)
end

#gunzipObject

gunzip the string


393
394
395
396
# File 'lib/epitools/core_ext/string.rb', line 393

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

#gzip(level = nil) ⇒ Object

gzip the string


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

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)


487
488
489
# File 'lib/epitools/core_ext/string.rb', line 487

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.


145
146
147
148
149
150
151
152
153
# File 'lib/epitools/core_ext/string.rb', line 145

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


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

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


363
364
365
# File 'lib/epitools/core_ext/string.rb', line 363

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


158
159
160
# File 'lib/epitools/core_ext/string.rb', line 158

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.


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

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.


261
262
263
# File 'lib/epitools/core_ext/string.rb', line 261

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

#sentencesObject


232
233
234
# File 'lib/epitools/core_ext/string.rb', line 232

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

#sha1Object

SHA1 the string


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

def sha1
  Digest::SHA1.hexdigest self
end

#sha256Object

SHA256 the string


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

def sha256
  Digest::SHA256.hexdigest self
end

#smashObject

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


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

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

#split_after(boundary) ⇒ Object


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

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

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


111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/epitools/core_ext/string.rb', line 111

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


137
138
139
# File 'lib/epitools/core_ext/string.rb', line 137

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


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

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

#strip_colorObject Also known as: strip_ansi

Remove ANSI color codes.


85
86
87
# File 'lib/epitools/core_ext/string.rb', line 85

def strip_color
  gsub(COLOR_REGEXP, '')
end

#tightenObject

Remove redundant whitespaces (not including newlines).


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

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

#titlecaseObject

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


48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/epitools/core_ext/string.rb', line 48

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)


64
65
66
# File 'lib/epitools/core_ext/string.rb', line 64

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.)


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

def to_base62
  to_i(16).to_base62
end

#to_base64Object Also known as: base64, encode64

Encode into a mime64/base64 string


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

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

#to_i_from_bytes(big_endian = false) ⇒ Object

Raw bytes to an integer (as big as necessary)


308
309
310
311
# File 'lib/epitools/core_ext/string.rb', line 308

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


290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'lib/epitools/core_ext/string.rb', line 290

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).


256
257
258
# File 'lib/epitools/minimal.rb', line 256

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.


624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/epitools/core_ext/string.rb', line 624

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


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

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).


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

def unmarshal
  Marshal.restore self
end

#urldecodeObject

Convert an URI's %XXes into regular characters.


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

def urldecode
  URI.unescape(self)
end

#urlencodeObject

Convert non-URI characters into %XXes.


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

def urlencode
  URI.escape(self)
end

#wordsObject


236
237
238
# File 'lib/epitools/core_ext/string.rb', line 236

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

#words_without_stopwordsObject Also known as: without_stopwords


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

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.


172
173
174
175
176
177
178
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
# File 'lib/epitools/core_ext/string.rb', line 172

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


217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/epitools/core_ext/string.rb', line 217

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