Module: Sutil
- Defined in:
- lib/modl/parser/sutil.rb
Class Method Summary collapse
-
.after(str, c) ⇒ Object
Get everything after char c.
-
.between(str, ch1, ch2) ⇒ Object
Get everything between ch1 and ch2 ch1 and ch2 must be different and ch1 must be before ch2 in the string e.g.
-
.head(str, n = nil) ⇒ Object
Keep the first n characters of a string.
- .replace(str, old, new) ⇒ Object
-
.tail(str, n = 1) ⇒ Object
Remove the first n characters from a string.
-
.toptail(str) ⇒ Object
Remove the first and last chars from a string.
-
.until(str, c) ⇒ Object
Keep everything until char c.
Class Method Details
.after(str, c) ⇒ Object
Get everything after char c
29 30 31 32 33 34 35 36 37 |
# File 'lib/modl/parser/sutil.rb', line 29 def self.after(str, c) return if str.nil? return str if c.nil? i = str.index(c) return '' if i.nil? str.slice(i + c.length, str.length) end |
.between(str, ch1, ch2) ⇒ Object
Get everything between ch1 and ch2 ch1 and ch2 must be different and ch1 must be before ch2 in the string e.g. Sutil.between(‘func(p1,p2)’, ‘(’, ‘)’) returns ‘p1,p2’
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/modl/parser/sutil.rb', line 42 def self.between(str, ch1, ch2) return if str.nil? return str if ch1.nil? || ch2.nil? || ch1 == '' || ch2 == '' return str if str.length < 3 first = str.index(ch1) second = str.rindex(ch2) if first > second tmp = first first = second second = tmp end return str if first == second str.slice(first + 1, second - first - 1) end |
.head(str, n = nil) ⇒ Object
Keep the first n characters of a string
12 13 14 15 16 17 18 |
# File 'lib/modl/parser/sutil.rb', line 12 def self.head(str, n = nil) return if str.nil? n = str.length - 1 if n.nil? # Strip last char by default str&.slice(0, n) end |
.replace(str, old, new) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/modl/parser/sutil.rb', line 67 def self.replace(str, old, new) return str if old.nil? || new.nil? || old.empty? || old == new result = str loop do break unless result.include?(old) result = result.sub(old, new) end result end |
.tail(str, n = 1) ⇒ Object
Remove the first n characters from a string
5 6 7 8 9 |
# File 'lib/modl/parser/sutil.rb', line 5 def self.tail(str, n = 1) return if n.negative? str&.slice(n, str.length) end |
.toptail(str) ⇒ Object
Remove the first and last chars from a string.
60 61 62 63 64 65 |
# File 'lib/modl/parser/sutil.rb', line 60 def self.toptail(str) return str if str.nil? return '' if str.length < 3 str&.slice(1, str.length - 2) end |
.until(str, c) ⇒ Object
Keep everything until char c
21 22 23 24 25 26 |
# File 'lib/modl/parser/sutil.rb', line 21 def self.until(str, c) return str if c.nil? || c.empty? i = str.index(c) i ? str&.slice(0, i) : str end |