Developing a little survey webapp, ran into problem that deals with ranges for rating type questions. So a rating's range could be:
1..10
-5..0
-5..5
'a'..'z'
'E'..'M'
and so on
The range is stored as a pair of varchars in database (start and end of range). So range always starts off as a string input.
What is the best way to take these string values and build a Ruby Range accordingly. I can't just go value.to_i as this won't work for string iteration. Having a bunch of if's seems ugly. Any better way?
Not as important, but worth asking: Also what if I wanted to make it all work with reversed range? Say 5-to-0 or G-to-A. I know that Ruby doesn't support reverse range (since it uses succ() to iterate). What would be the best way here?
Thanks in advance!
Update:
Based on Wouter de Bie's suggestion I've settled for this:
def to_int_or_string(str)
return str.match(/^-?\d+$/) ? str.to_i : str.strip
end
def ratings_array(from, to)
from = to_int_or_string(from)
to = to_int_or_string(to)
from > to ? Range.new(to, from).to_a.reverse : Range.new(from, to).to_a
end
Any thoughts?