Created
October 5, 2011 14:53
-
-
Save tomas-stefano/1264620 to your computer and use it in GitHub Desktop.
Range Parser. Transform a string in an Array of values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Tributario | |
class RangeParser | |
attr_reader :range_string | |
def initialize(word) | |
@range_string = word | |
end | |
# Parse the string and return an array of numbers | |
# | |
# ==== Returns | |
# Array[Class] | |
# | |
# ==== Examples | |
# | |
# RangeParser.new('1-4').parse! # => [1,2,3,4] | |
# RangeParser.new('1').parse! # => [1] | |
# RangeParser.new('1; 20-22').parse! # => [1, 20, 21, 22] | |
# | |
def parse! | |
@range_string.split(';').collect do |number| | |
numbers = number.split('-').collect { |n| Integer(n) } | |
numbers = Range.new(numbers[0], numbers[1]).to_a if numbers.size == 2 | |
numbers | |
end.flatten | |
end | |
# The string is valid when pass when have '-' between numbers or ';' between numbers | |
# | |
# ==== Returns | |
# Boolean[Class] | |
# | |
# ==== Examples | |
# | |
# RangeParser.new('1').valid? # => true | |
# RangeParser.new('1-100').valid? # => true | |
# RangeParser.new('1; 100').valid? # => true | |
# RangeParser.new('1; 100-200').valid? # => true | |
# RangeParser.new('1- 100-200').valid? # => false | |
# RangeParser.new('1..100-200').valid? # => false | |
# | |
def valid? | |
@range_string.gsub(' ','').split(";").all? { |str| (str.match(/^((\d+)|(\d+)-(\d+))$/) != nil) } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment