Class: Pcut::RangeIndex

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

Constant Summary collapse

FORMAT =
%r/\A\s*(\-)?(\d+)(\-)?\s*\z/

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(index, backward, forward) ⇒ RangeIndex

Returns a new instance of RangeIndex.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/pcut/range_index.rb', line 10

def initialize(index, backward, forward)
  unless index.is_a?(Fixnum)
    raise ArgumentError, "invalid index: #{index}"
  end
  unless backward == true || backward == false
    raise ArgumentError, "invalid backward spec: #{backward}"
  end
  unless forward == true || forward == false
    raise ArgumentError, "invalid forward spec: #{forward}"
  end

  @index    = index
  @backward = backward
  @forward  = forward
end

Instance Attribute Details

#indexObject (readonly)

Returns the value of attribute index.



8
9
10
# File 'lib/pcut/range_index.rb', line 8

def index
  @index
end

Class Method Details

.parse(str) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/pcut/range_index.rb', line 26

def self.parse(str)
  unless str.is_a?(String)
    raise ArgumentError, "#{str.to_s} is not string"
  end
  unless str =~ FORMAT
    raise ArgumentError, "invalid range index expression: #{str}"
  end

  backward = $1 ? true : false
  forward  = $3 ? true : false
  index    = $2.to_i

  if backward && forward
    raise ArgumentError, "backward, forward both specified: #{str}"
  end
  if 0 == index
    raise ArgumentError, "zero cannot be specified: #{str}"
  end

  self.new(index, backward, forward)
end

Instance Method Details

#include_backward?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/pcut/range_index.rb', line 48

def include_backward?
  @backward
end

#include_forward?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/pcut/range_index.rb', line 52

def include_forward?
  @forward
end

#to_sObject



56
57
58
59
60
61
62
# File 'lib/pcut/range_index.rb', line 56

def to_s
  "%s%d%s" % [
    include_backward? ? "-" : "",
    @index,
    include_forward?  ? "-" : "",
  ]
end