将 Ruby 字符串范围转换为 Range 对象的最佳方法是什么 [英] What is the best way to convert a Ruby string range to a Range object
问题描述
我有一些 Ruby 代码,它在命令行中采用以下格式获取日期:
I have some Ruby code which takes dates on the command line in the format:
-d 20080101,20080201..20080229,20080301
我想运行 20080201
和 20080229
之间的所有日期以及列表中存在的其他日期.
I want to run for all dates between 20080201
and 20080229
inclusive and the other dates present in the list.
我可以获得字符串 20080201..20080229
,那么将其转换为 Range 实例的最佳方法是什么?目前,我正在使用 eval
,但感觉应该有更好的方法.
I can get the string 20080201..20080229
, so is the best way to convert this to a Range instance? Currently, I am using eval
, but it feels like there should be a better way.
@Purfideas 我正在寻找一个更通用的答案,用于将 int..int
类型的任何字符串转换为我猜的范围.
@Purfideas I was kind of looking for a more general answer for converting any string of type int..int
to a Range I guess.
推荐答案
然后就去做
ends = '20080201..20080229'.split('..').map{|d| Integer(d)}
ends[0]..ends[1]
无论如何,出于安全原因,我不建议使用 eval
anyway I don't recommend eval, for security reasons
这篇关于将 Ruby 字符串范围转换为 Range 对象的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!