-3

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

??

oldergod
  • 15,033
  • 7
  • 62
  • 88
GedankenNebel
  • 2,437
  • 5
  • 29
  • 39

3 Answers3

2

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

Alexander Randa
  • 868
  • 4
  • 7
1

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>
Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71
  • No, it doesn't do exactly the same thing. The JavaScript notation is limited to a subset of symbol keys whereas the hashrocket works with any valid key. More details over here: http://stackoverflow.com/a/8675314/479863 – mu is too short Nov 17 '12 at 17:34
0

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

krichard
  • 3,699
  • 24
  • 34