Class: String

Inherits:
Object show all
Defined in:
lib/ruby/to_d.rb,
lib/ruby/blank.rb,
lib/ruby/string.rb,
lib/ruby/to_date.rb,
lib/ruby/to_time.rb

Constant Summary

BIGDECIMAL =
/\A[+-]?            (?# optional leading sign            )
 (?:
   (?:\d+\.?\d*)  | (?# whole with optional decimal or ..)
   (?:\d*?\.?\d+) ) (?# optional whole with decimal      )
 (?:E[+-]?\d+)?     (?# optional exponent                )
\Z/ix

Instance Method Summary (collapse)

Instance Method Details

- (String) at(n)

Return the one-character string at the given index

Examples:

"abc".at(0)   #=> "a"
"abc".at(2)   #=> "c"

Raises:

  • (ArgumentError)


12
13
14
15
# File 'lib/ruby/string.rb', line 12

def at(n)
  raise ArgumentError, "n must be positive" if n < 0
  self[n, 1] unless n >= length
end

- (Boolean) blank?

True if the string is empty? or contains all whitespace

Examples:

"abc".blank?    #=> false
"   ".blank?    #=> true
"".blank?       #=> true


10
11
12
# File 'lib/ruby/blank.rb', line 10

def blank?
  self !~ /\S/
end

- (Boolean) defined_at?(n)

True if the string is long enough such that #at is defined for the given n

Examples:

"abc".defined_at?(0)  #=> true
"abc".defined_at?(3)  #=> false


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

def defined_at?(n)
  n < length
end

- (String) drop(n)

Return the string with n characters removed from the front

Examples:

"abc".drop(0)   #=> "abc"
"abc".drop(2)   #=> "c"

Raises:

  • (ArgumentError)


26
27
28
29
# File 'lib/ruby/string.rb', line 26

def drop(n)
  raise ArgumentError, "n must be positive" if n < 0
  (length >= n) ? self[n..-1] : ""
end

- position

To make String compatible with the Stupidedi::Reader::Input interface, we have to define #position... shameful!



70
71
72
# File 'lib/ruby/string.rb', line 70

def position
  nil
end

- (Boolean) present?



14
15
16
# File 'lib/ruby/blank.rb', line 14

def present?
  self =~ /\S/
end

- (Array(String, String)) split_at(n)

Split the string in two at the given position

Examples:

"abc".split_at(0)   #=> ["", "abc"]
"abc".split_at(2)   #=> ["ab", "c"]


54
55
56
# File 'lib/ruby/string.rb', line 54

def split_at(n)
  [take(n), drop(n)]
end

- (String) take(n)

Return the first n characters from the front

Examples:

"abc".take(0)   #=> ""
"abc".take(2)   #=> "ab"

Raises:

  • (ArgumentError)


40
41
42
43
# File 'lib/ruby/string.rb', line 40

def take(n)
  raise ArgumentError, "n must be positive" if n < 0
  self[0, n]
end

- to_d



28
29
30
31
32
33
34
# File 'lib/ruby/to_d.rb', line 28

def to_d
  if BIGDECIMAL =~ self
    BigDecimal(to_s)
  else
    raise ArgumentError, "#{inspect} is not a valid number"
  end
end

- to_date



13
14
15
# File 'lib/ruby/to_date.rb', line 13

def to_date
  Date.parse(self)
end

- to_time



18
19
20
# File 'lib/ruby/to_time.rb', line 18

def to_time
  Time.parse(self)
end