Class: Basic101::BasicString

Inherits:
BasicObject
Includes:
BasicComparisons, Comparable
Defined in:
lib/basic101/basic_string.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from BasicComparisons

comparison_op

Methods inherited from BasicObject

#eval, #to_float, #to_integer, #to_numeric, #type_name, type_name

Constructor Details

#initialize(value) ⇒ BasicString

Returns a new instance of BasicString.



12
13
14
# File 'lib/basic101/basic_string.rb', line 12

def initialize(value)
  @value = value.to_s
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



10
11
12
# File 'lib/basic101/basic_string.rb', line 10

def value
  @value
end

Instance Method Details

#+(other) ⇒ Object



68
69
70
# File 'lib/basic101/basic_string.rb', line 68

def +(other)
  BasicString.new(value + other.to_string.value)
end

#<=>(other) ⇒ Object



16
17
18
19
# File 'lib/basic101/basic_string.rb', line 16

def <=>(other)
  return nil unless other.is_a?(self.class)
  value <=> other.value
end

#ascObject



72
73
74
75
# File 'lib/basic101/basic_string.rb', line 72

def asc
  raise InvalidArgumentError if @value.empty?
  BasicInteger.new(@value.chars.first.ord)
end

#left(count) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/basic101/basic_string.rb', line 33

def left(count)
  count = count.to_i
  if count < 0
    raise InvalidArgumentError
  end
  BasicString.new(@value[0...count])
end

#lengthObject



50
51
52
# File 'lib/basic101/basic_string.rb', line 50

def length
  BasicInteger.new(@value.size)
end

#mid(start, count = nil) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/basic101/basic_string.rb', line 54

def mid(start, count = nil)
  start = start.to_i
  count = count && count.to_i
  raise InvalidArgumentError if start < 1
  raise InvalidArgumentError if count && count < 1
  start -= 1
  substring = if count
                @value[start, count]
              else
                @value[start..-1]
              end
  self.class.new(substring)
end


25
26
27
# File 'lib/basic101/basic_string.rb', line 25

def print_new_line(output)
  output.print "\n"
end


21
22
23
# File 'lib/basic101/basic_string.rb', line 21

def print_string(output)
  output.print @value
end

#right(count) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/basic101/basic_string.rb', line 41

def right(count)
  count = count.to_i
  if count < 0
    raise InvalidArgumentError
  end
  substring = @value[/.{0,#{count}}$/]
  BasicString.new(substring)
end

#strObject



81
82
83
# File 'lib/basic101/basic_string.rb', line 81

def str
  self
end

#to_stringObject



29
30
31
# File 'lib/basic101/basic_string.rb', line 29

def to_string
  self
end

#valObject



77
78
79
# File 'lib/basic101/basic_string.rb', line 77

def val
  BasicFloat.new(@value.to_f).simplest
end