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
页: 1
范围被储存在数据库中(范围开始和结束)。 因此,范围总是作为强有力的投入而开始。
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?
提前感谢!
最新情况:
根据Wouter de Bie的建议,我就此作了决定:
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
任何想法?