简体   繁体   中英

Why does this work under Ruby 1.9.3 and not under 1.8.7?

I'm building a custom Form Builder in Rails and i've been following this great Rails Cast video ( http://railscasts.com/episodes/311-form-builders?view=asciicast ).

Ryan uses a line like this:

<%= form_for @project, builder: BootstrapFormBuilder do |f| %>

But under 1.8.7 this bombs out with a cryptic error message.

What changed in Ruby 1.9.3 that makes this now work?

By the way, the following does work in 1.8.7, but why?

<%= form_for(@project, :builder => BootstrapFormBuilder) do |f| %>

What changed in Ruby 1.9.3 that makes this now work?

There is a new syntax for Hash literals whose keys are Symbol s which are valid identifiers. Instead of

{ :foo => 'bar', :baz => 42 }

You can now also write

{ foo: 'bar', baz: 42 }

This syntax was introduced in 1.9.0.

By the way, the following does work in 1.8.7, but why?

Because that's the same thing, just written using a different syntax.

The hash syntax has been extended to let users use a JavaScript like style.

# Old syntax
old_hash = { :name => 'Ruby', :influences => ['Perl', 'Python', 'Smalltalk'] }

# New syntax (Ruby 1.9 only)
new_hash = { name: 'Ruby', influences: ['Perl', 'Python', 'Smalltalk'] }

http://peepcode.com/blog/2011/rip-ruby-hash-rocket-syntax

The hash syntax changed in Ruby 1.9. In all versions of Ruby you can use key => value , but Ruby 1.9 has a new key: value syntax. This is why your second example works, but the first doesn't.

Because of this part:

builder: BootstrapFormBuilder

This creates a hash, but the syntax is only allowed in Ruby 1.9+. Before, to create a hash, you had to do

:builder => BootstrapFormBuilder

Which is why the second line works in 1.8.

Ruby 1.9 introduced an alternative hash syntax:

# Ruby 1.8 and 1.9
h = { :a => 1, :b => 2 }

# Ruby 1.9 only
h = { a: 1, b: 2 }

It should be noted that a: is just a syntactic sugar for :a => , that is a is still a symbol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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