ruby - 将哈希传递给 p 会导致语法错误

标签 ruby syntax-error

为什么我会得到这个?

p {a:3}
# => syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
# => p {a:3}
           ^

最佳答案

Ruby 的解析引擎有一些奇怪的地方。一是某些内容需要用括号括起来。

例如,这应该可行。

p({a:3})

或者这个

hash = { a: 3 } 
p hash

正如另一个答案所指出的。其原因是解释器的处理如下。

# Input
p { a: 3 }

# What the interpreter sees
p do
  a: 3
end

Kernel#p 不支持 block ,因此您必须使用括号。

关于ruby - 将哈希传递给 p 会导致语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20051417/

相关文章:

ruby-on-rails - 使用 rake 数据库 :migrate inside another task leaves pending migrations

ruby - sinatra hello world 示例如何工作?

mysql - Ruby on Rails MySQL #08S01Bad handshake - 降级 MySQL?

mysql - 找不到mySQL请求错误

PHP mysqli_fetch_array() 不会在 while 循环中将所有选择查询插入到表中

php - 解析错误: syntax error, unexpected '[' when uploaded into the hosting server [closed]

ruby - Ruby 的 PostgreSQL 适配器的正确名称是什么?

sql - '-' 附近的语法不正确。(Microsoft SQL Server Native Client 10.0)

ios - 无法使用类型为 'findObjectsInBackgroundWithBlock' 的参数列表调用 '(([AnyObject]!, NSError!) -> Void)'

c - 当 Ruby 中的 system() 调用时,GCC 无法编译