0

I was reading the source code of a gem "activerecord-postgres-earthdistance".

While running the migration script, it threw an error on the following method

def order_by_distance lat, lng, order: "ASC"

It gave an error for order: "ASC"

syntax error, unexpected tLABEL

Isn't this valid Ruby syntax?

JunaidKirkire
  • 878
  • 1
  • 7
  • 17

2 Answers2

2

Ruby 2.0 supports keywords arguments

[5] pry(main)> def bar(a: "name", b: "fem"); puts a,b end
[6] pry(main)> bar(a: "John", b: "Male")
John
Male
[7] pry(main)> bar("John", "Male")
ArgumentError: wrong number of arguments (2 for 0)
from (pry):5:in `bar'

However the above is not valid in 1.9 see below:

ruby 1.9.3p448 (2013-06-27 revision 41675) [x86_64-darwin12.4.0]
[2] pry(main)> def bar(a: "name", b: "fem"); puts a,b end
SyntaxError: unexpected ',', expecting $end
def bar(a: "name", b: "fem"); puts a,b end
              ^
[2] pry(main)> def bar(a: "name"); puts a end
SyntaxError: unexpected ')', expecting $end
def bar(a: "name"); puts a end
              ^

For better understanding you can read here and here

bjhaid
  • 9,592
  • 2
  • 37
  • 47
0
def order_by_distance(lat, lng, hash={})
  puts hash[:order]
end

=> order_by_distance(lat, lng, order: "ASC")
=> "ASC"

use hash arguments in ruby

Community
  • 1
  • 1
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103