Ruby中简单的自定义范围(Simple custom range in Ruby)

系统教程 行业动态 更新时间:2024-06-14 16:55:57
Ruby中简单的自定义范围(Simple custom range in Ruby)

我有一个Rails的named_scope,它使用一个条件从表中抽取一周中的特定日子,如下所示:

:conditions => [ 'EXTRACT(DOW FROM bookdate) IN (?)', (1..6).to_a ]

1。6日期范围将是一个变量,具体取决于用户想要的日期,

哪个产生这个SQL

(EXTRACT(DOW FROM bookdate) IN (1,2,3,4,5,6)

我的问题是,一周的日子不是一个简单的范围...即1..6工作正常(周一...周六),但说6..2将无法正常工作(周六 - 周二)...无论是作为红宝石范围还是需要6,7,1,2而不是6,5,4,3,2(假设6..2在红宝石中工作,它没有)。

我怎样才能创建一个适合这样的日期范围的星期几的自定义范围?

有任何想法吗?

谢谢,

I have a Rails named_scope which is using a condition to pull specific days of the week from the table like so:

:conditions => [ 'EXTRACT(DOW FROM bookdate) IN (?)', (1..6).to_a ]

The 1..6 date range will be a variable depending on the dates the user wants,

Which produces this SQL

(EXTRACT(DOW FROM bookdate) IN (1,2,3,4,5,6)

My problem is that the days of the week are not a simple range... ie 1..6 works fine (Mon...Sat), but say 6..2 will not work correctly (Sat-Tues)... either as a ruby range or as it would need to be 6,7,1,2 and not 6,5,4,3,2 (assuming 6..2 worked in ruby, which it doesn't).

How can I create a custom range for days of the week that would accommodate a date range like this?

Any ideas?

Thanks,

最满意答案

如果你想要一个函数来生成包含在以下内容中的值的范围:conditions适用于Sat-Tues和Mon-Sat等范围的:conditions如何:

def day_range(from, to) if from <= to (from..to).to_a else (from..7).to_a + (1..to).to_a end end

例如

irb(main):032:0> day_range(1, 6) => [1, 2, 3, 4, 5, 6] irb(main):033:0> day_range(6, 2) => [6, 7, 1, 2]

然后,如果需要,这只是将日期名称映射到日期数字的情况。

If you want a function to generate the range of values for inclusion in :conditions that will work for ranges like Sat-Tues as well as Mon-Sat how about:

def day_range(from, to) if from <= to (from..to).to_a else (from..7).to_a + (1..to).to_a end end

e.g.

irb(main):032:0> day_range(1, 6) => [1, 2, 3, 4, 5, 6] irb(main):033:0> day_range(6, 2) => [6, 7, 1, 2]

Then it is just a case of mapping the day names to the day numbers if required.

更多推荐

本文发布于:2023-04-10 11:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/195a1a6ee808f50494ee0c6f6bcc54ff.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   简单   Ruby   range   custom

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!