-1

What is the difference between these two lines to validate a model's attribute?

validates :last_name, :length => { :maximum => 32 }

validates :last_name, length: { maximum: 32 }

The first uses :attribute => and the second uses attribute:.

juliano.net
  • 7,982
  • 13
  • 70
  • 164
  • The second is the new way to represent a hash value as of Ruby version 1.9. Behavior for the two examples you show should be identical. The older way (your first one) doesn't seem to be deprecated, so both will work. – lurker May 23 '15 at 22:53

2 Answers2

1

The difference between the two is the syntax for defining a Hash of key/value pairs. It depends on the Ruby version you're using.

The first one is supported in both Ruby 1.8 and 1.9+:

:key => :value

And the second one is supported in Ruby 1.9+ only:

key: :value

If you're using Ruby 1.9, you should probably use the latter, since it seems to be the preferred way in the community. I personally also think its cleaner code.

There's one difference though. You can't use the latter when your key is a string unless you're using Ruby 2.2. This will only work in Ruby 2.2+:

{ 'key': :value }

To use strings as keys in anything lower than Ruby 2.2, you'll have to use the 'hash rocket':

{ :'key' => 'value }
Kevin
  • 1,213
  • 10
  • 13
0

There is no difference,

{ symbol_key: value }

is just cleaner-looking than

{ :symbol_key => value }

For string keys you still need to use the "rocket" to declare a key's value, like so:

{ "string_key" => value }

And in fact, if you open the ruby console and type

{ symbol_key: "value" }

it outputs { :symbol_key => "value" } suggesting that { symbol_key: "value" } translates to the rocket syntax and it's only available to look nicer.

nevets138
  • 80
  • 8