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:
.
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:
.
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 }
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.