繁体   English   中英

Ruby(rails)构造函数调用给出语法错误

[英]Ruby (rails) constructor call giving syntax error

我正在学习Sam Ruby的《用Rails开发敏捷Web开发》一书,学习Rails开发,并且在调用模型的构造函数时遇到语法错误。 我发现了两种使用备用语法来调用构造函数的方法,但是我真的很想知道为什么本书中使用的语法在我的开发环境中不起作用。

本书使用的语法中,键/值对被括号括起来,如下所示:

product = Product.new (title: "foo", description: "yyy")

此代码在单元测试中。 当我运行“ rake test:units”时,出现以下错误:

product = Product.new (title: "foo", description: "yyy")

__ _ __ _ __ __ _ _ _ __ __ _ __ __ _ _ _ __ __ ^

ruby_book_demo / depot / test / unit / product_test.rb:16:语法错误,意外的tLABEL

注意,通过执行以下操作,我已经能够解决语法错误:

product = Product.new title: "foo", description: "yyy" #WORKS

要么

product = Product.new ({title: "foo", description: "yyy"}) # WORKS!

但我真的很想知道为什么会出错。 我正在使用jruby:

jruby -v jruby 1.6.7.2(ruby-1.9.2-p312)(2012-05-01 26e08ba)

谢谢。

Product.new和括号之间不能有空格:

Product.new(title: 'foo', description: 'bar')

它没有括号的原因是因为它们是可选的,并且在这种情况下需要空格。

暂无
暂无

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

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