Class: RangeSentenceParser

Inherits:
Object
  • Object
show all
Defined in:
lib/range_sentence_parser.rb,
lib/range_sentence_parser/version.rb,
lib/range_sentence_parser/invalid_sentence_error.rb

Defined Under Namespace

Classes: InvalidSentenceError

Constant Summary collapse

VERSION =
"0.0.3"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sentence) ⇒ RangeSentenceParser

Returns a new instance of RangeSentenceParser.



41
42
43
# File 'lib/range_sentence_parser.rb', line 41

def initialize(sentence)
  self.sentence = sentence
end

Class Method Details

.invalid?(sentence) ⇒ Boolean

Performs the opposite of valid?

Usage:

RangeSentenceParser.invalid?('1990; 1995-2000; 2005') # => false
RangeSentenceParser.invalid?('1990, 1995-2000, 2005') # => true

Returns:

  • (Boolean)


36
37
38
39
# File 'lib/range_sentence_parser.rb', line 36

def self.invalid?(sentence)
  range_sentence_parser = self.new(sentence)
  range_sentence_parser.invalid?
end

.parse!(sentence) ⇒ Object

Parse the sentence and return a collection of numbers and/or ranges

Usage:

RangeSentenceParser.parse!('')                      # => []
RangeSentenceParser.parse!('1990')                  # => [1990]
RangeSentenceParser.parse!('1990; 1995')            # => [1990, 1995]
RangeSentenceParser.parse!('1990-1995')             # => [1990..1995]
RangeSentenceParser.parse!('1990; 1995-2000; 2005') # => [1990, 1995..2000, 2005]


14
15
16
17
# File 'lib/range_sentence_parser.rb', line 14

def self.parse!(sentence)
  range_sentence_parser = self.new(sentence)
  range_sentence_parser.parse!
end

.valid?(sentence) ⇒ Boolean

Validate the sentence and return true or false

Usage:

RangeSentenceParser.valid?('1990; 1995-2000; 2005') # => true
RangeSentenceParser.valid?('1990, 1995-2000, 2005') # => false

Returns:

  • (Boolean)


25
26
27
28
# File 'lib/range_sentence_parser.rb', line 25

def self.valid?(sentence)
  range_sentence_parser = self.new(sentence)
  range_sentence_parser.valid?
end

Instance Method Details

#invalid?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/range_sentence_parser.rb', line 61

def invalid?
  !valid?
end

#parse!Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/range_sentence_parser.rb', line 45

def parse!
  raise InvalidSentenceError if invalid?

  sentence.split(';').map do |number|
    if number =~ /(\d+)-(\d+)/
      Range.new($1.to_i, $2.to_i)
    else
      number.to_i
    end
  end
end

#valid?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/range_sentence_parser.rb', line 57

def valid?
  sentence.empty? || sentence =~ /\A\d+(-\d+)?(\s*;\s*\d+(-\d+)?)*;?\z/
end