为什么 Rails 可以使用 `if` 作为哈希键,但在 Ruby 中不能 [英] Why Rails can use `if` as hash key but not in Ruby

查看:30
本文介绍了为什么 Rails 可以使用 `if` 作为哈希键,但在 Ruby 中不能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在纯 Ruby irb 中,不能输入 {if: 1}.该语句不会终止,因为 irb 认为 if 不是一个符号,而是 if 语句的开始.

In pure Ruby irb, one cannot type {if: 1}. The statement will not terminate, because irb thinks if is not a symbol but instead the beginning of an if statement.

那么为什么 Rails 可以有接受 if 作为参数的 before_filter 呢?该指南的代码如下:

So why can Rails have before_filter which accept if as parameters? The guide have codes like:

class Order < ApplicationRecord
  before_save :normalize_card_number, if: :paid_with_card?
end

同样的事情发生在 unless 上.

Same thing happens to unless as well.

推荐答案

众所周知,IRb 的解析器被破坏了.(事实上​​,你遇到的这个 bug 几个月前就已经报告过了:Bug #12177:Usingif: 作为哈希符号,在 irb 控制台中使用新的哈希语法不起作用.)忽略它.IRb 和 Ruby 之间还有其他行为差异,语义差异,而不仅仅是句法差异.例如.在顶层定义的方法隐式public而不是隐式private,因为它们应该是.

IRb's parser is well-known to be broken. (In fact, the very bug you encountered was already reported months ago: Bug #12177: Using if: as symbol in hash with new hash syntax in irb console is not working.) Just ignore it. There are also other differences in behavior between IRb and Ruby, semantic ones, not just syntactic. E.g. methods defined at the top-level are implicitly public instead of implicitly private as they should be.

IRb 尝试使用自己的解析器解析代码以找出答案,例如是在您点击 ENTER 时将其提交给引擎还是在下一行等待您继续代码.但是,由于Ruby的语法极其复杂,很难正确解析,而且IRb的解析器与Ruby的有偏差.

IRb tries to parse the code with its own parser to figure out, e.g. whether to submit it to the engine when you hit ENTER or wait for you on the next line to continue the code. However, because Ruby's syntax is extremely complex, it is very hard to parse it correctly, and IRb's parser is known to deviate from Ruby's.

其他 REPL 采取不同的方法,例如Pry 实际上使用 Ruby 的解析器而不是它自己的解析器.

Other REPLs take different approaches, e.g. Pry actually uses Ruby's parser instead of its own.

这篇关于为什么 Rails 可以使用 `if` 作为哈希键,但在 Ruby 中不能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆