Friday, February 8, 2008

Convert String to Range

class String
def to_range
case self.count('.')
when 2
elements = self.split('..')
return Range.new(elements[0].to_i, elements[1].to_i)
when 3
elements = self.split('...')
return Range.new(elements[0].to_i, elements[1].to_i-1)
else
raise ArgumentError.new("Couldn't convert to Range:
#{str}")
end
end
end

p "1..2".to_range
p "1...2".to_range
p "1.2".to_range

output:
1..2
1..1
rng.test:11:in `to_range': undefined local variable or method `str'
for "1.2":String (NameError)
from rng.test:18


http://www.ruby-forum.com/topic/141926#629921

2 comments:

Yorga Babuscan said...

Congratulations!

This method is exactly what I was looking for.

Regards, Yorga.

Humberto Pinto said...

maybe eval("1..4") would be quicker to implement