Class: String

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

Instance Method Summary collapse

Instance Method Details

#each_index(x) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/string.rb', line 3

def each_index(x)
  raise 'Block required' unless block_given?
  return if empty? || x.nil?

  i = 0
  while true
    i = index(x, i)
    return if i.nil?

    yield i
    i += 1

    return if i + 1 == length
  end
end

#index_of_split(other) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/string.rb', line 43

def index_of_split(other)
  last_idx = (other.length - 1)

  (0..last_idx).step do |i|
    part = other[i..last_idx]      
    return part.length - 1 if start_with?(part)
  end

  nil
end

#rindex_of_split(other) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/string.rb', line 54

def rindex_of_split(other)
  last_idx = (other.length - 1)

  (0..last_idx).step do |i|
    part = other[0..(last_idx - i)]
    return length - part.length if end_with?(part)
  end

  nil
end

#strip_other(str) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/string.rb', line 19

def strip_other(str)
  start_i = 0
  new_length = length

  if start_with?(str)
    start_i += str.length
    new_length -= str.length
  end

  if end_with?(str)
    new_length -= str.length
  end

  self[start_i, new_length]
end

#underscoreObject



35
36
37
38
39
40
41
# File 'lib/string.rb', line 35

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