Ruby default values error

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?

Answers


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


def order_by_distance(lat, lng, hash={})
  puts hash[:order]
end

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

use hash arguments in ruby


Need Your Help

Output utf-8 characters in django as json

python django json encoding utf-8

I am trying to output some json with cyrillic characters in it.

Rails form_for Error | How to Bind Nested ActiveRecord Object to Form

ruby-on-rails ruby ruby-on-rails-3 activerecord

I was developing a Ruby on Rails application. It has a nested route like so: