Question

Is this code aquivalent

class Product < ActiveRecord::Base
  validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/,
    :message => "Only letters allowed" }
end

to this code:

class Product < ActiveRecord::Base
  validates :legacy_code, format: { with:/\A[a-zA-Z]+\z/,
    message:"Only letters allowed" }
end

??

Was it helpful?

Solution

Yes, this codes are equivalent in ruby 1.9.
{:key => vales} - is a hash syntax in ruby 1.8
{key: value} - is a new hash syntax, it was added in ruby 1.9

OTHER TIPS

Yes. As long you aren't using Ruby 1.8, you can use {a: 'b'} syntax. It does exactly what {:a => 'b'} does, it's just shorter.

When ran in IRB, both examples show identical results (in Ruby 1.9).

$ irb1.9
irb(main):001:0> {:a => 'b'}
=> {:a=>"b"}
irb(main):002:0> {a: 'b'}
=> {:a=>"b"}
irb(main):003:0>

But when running in Ruby 1.8, {a: 'b'} doesn't work.

$ irb1.8
irb(main):001:0> {:a => 'b'}
=> {:a=>"b"}
irb(main):002:0> {a: 'b'}
SyntaxError: compile error
(irb):2: odd number list for Hash
{a: 'b'}
   ^
(irb):2: syntax error, unexpected ':', expecting '}'
{a: 'b'}
   ^
(irb):2: syntax error, unexpected '}', expecting $end
        from (irb):2
irb(main):003:0>

If you are using ruby 1.9 then it is valid and also equivalent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top