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

rob*_*son 1 ruby constructor ruby-on-rails syntax-error ruby-on-rails-3

我正在使用Sam Ruby的"Agile Web Development With Rails"一书学习Rails开发,当我调用模型的构造函数时,我遇到语法错误.我找到了两种使用替代语法调用构造函数的方法,但我真的很想知道为什么本书中使用的语法在我的开发环境中不起作用.

本书使用语法,其中键/值对由括号括起来,类似于:

product = Product.new (title: "foo", description: "yyy")
Run Code Online (Sandbox Code Playgroud)

此代码在单元测试中.当我运行'rake test:units'时,我收到以下错误:

product = Product.new (title: "foo", description: "yyy")
Run Code Online (Sandbox Code Playgroud)

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

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

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

product = Product.new title: "foo", description: "yyy" #WORKS
Run Code Online (Sandbox Code Playgroud)

要么

product = Product.new ({title: "foo", description: "yyy"}) # WORKS!
Run Code Online (Sandbox Code Playgroud)

但我真的很想知道为什么我得到错误.我正在使用jruby:

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

谢谢.

Pet*_*own 5

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

Product.new(title: 'foo', description: 'bar')
Run Code Online (Sandbox Code Playgroud)

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