简体   繁体   English

Rails:Date.today - 1.day

[英]Rails: Date.today - 1.day

Using the rails console, I just got bit by this: 使用rails控制台,我得到了一点:

Assume today is December 11. 假设今天是12月11日。

Date.today-1.day   # December 10  (no spaces)
Date.today - 1.day # December 10  (a space on both sides of the minus sign)
Date.today -1.day  # December 11  whaaaat?
Date.today -5.days # Still december 11!

Can someone explain what's going on here? 有人能解释一下这里发生了什么吗? I am a little worried about how easy this could be missed in code. 我有点担心代码中容易错过这个问题。 Any other suggestions on how to code this? 关于如何编码的任何其他建议?

The difference you are seeing is caused by the way how ruby parses your code. 您看到的差异是由ruby解析代码的方式引起的。 In your case, you have stumbled about a syntactic nuance which greatly changes how the code is evaluated. 在您的情况下,您偶然发现了语法上的细微差别,这会大大改变代码的评估方式。

Your first two examples are actually expressions involving an operation on an object. 前两个示例实际上是涉及对象操作的表达式。 Thus 从而

Date.today-1.day
Date.today - 1.day

are both equivalent to 都等同于

Date.today.send(:-, 1.day)
# a "fancy" way to write
Date.today - 1.day

Your second two examples 你的第二个例子

Date.today -1.day
Date.today -5.days

are actually direct method calls on the Date.today method and are thus equivalent to 实际上是对Date.today方法的直接方法调用,因此相当于

Date.today( (-1).day )

This is because the minus is interpreted as a prefix to the 1 (and thus is parsed as the number -1). 这是因为减号被解释为1的前缀(因此被解析为数字-1)。 This interpretation is possible and doesn't throw any errors because of two properties of ruby: 由于ruby的两个属性,这种解释是可能的,并且不会引发任何错误:

  • Parenthesis are optional when calling methods as long as the result is unambiguous 只要结果是明确的,在调用方法时,括号是可选的
  • Date.today accepts an optional argument denoting calendar used Date.today接受表示所用日历的可选参数

The actual results you receive depend a bit on your environment as Rails seems to override some Date methods here. 您收到的实际结果取决于您的环境,因为Rails似乎在这里覆盖了一些Date方法。 In plain Ruby, you would get different dates back but it would still work. 在简单的Ruby中,你会得到不同的日期,但它仍然可以工作。

When you don't add a space after the minus sign, ruby takes it as a parameter for the function today. 如果在减号后面没有添加空格,ruby会将其作为今天函数的参数。 This function can receive one parameter. 此功能可以接收一个参数。 See here 看到这里

Your problem is a little syntax problem. 您的问题是一个小的语法问题。

This works fine for me 这对我来说很好

Date.today
# => Sun, 18 May 2014

Date.today() - 1.day
# => Sat, 17 May 2014

An prettier option is 更漂亮的选择是

Date.yesterday
# => Sat, 17 May 2014

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM