Ruby:将字符串转换为整数或在必要时将其保留为字符串的最佳方法?
开发一个小型调查网络应用程序,遇到了处理评级类型问题范围的问题。 因此,评级的范围可以是:
1..10
-5..0
-5..5
'a'..'z'
'E'..'M'
等等
该范围作为一对 varchar 存储在数据库中(范围的开始和结束)。因此范围始终以字符串输入开始。
获取这些字符串值并相应构建 Ruby Range 的最佳方法是什么? 我不能只使用 value.to_i 因为这不适用于字符串迭代。有一堆 if 看起来很难看。还有更好的办法吗?
不那么重要,但值得问: 另外,如果我想让它在反向范围内工作怎么办?比如说 5 对 0 或 G 对 A。我知道 Ruby 不支持反向范围(因为它使用 succ() 进行迭代)。这里最好的方法是什么?
提前致谢!
更新:
根据 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
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行以下操作。
这同时考虑了正值和负值范围
You can do something like the following.
This takes care of both the positive and the negative ranges
使用 Range.new:
如果 varchar 包含引号,则可以使用 eval 来获取正确的范围:
否则,您可以使用 value.to_i 来确定 varchar 中是数字还是字符串:
当然可以是很好地提取到一个方法中:
要反转您的范围,您必须首先将其转换为数组:
Use Range.new:
If you're varchars contain quotes, you can use eval to get the right ranges:
Otherwise you could use value.to_i to figure out if it was a number or a string in the varchar:
Which of course can be nicely extracted into a method:
To reverse your range, you have to convert it to an array first: