Default parameter values for methods in Ruby 1.9

Hi, I expected that the following is valid in Ruby 1.9:

def get_element(auid, document=nil, selector, check_etag=true)
[…]
end

However I get an error:

syntax error, unexpected ‘=’, expecting ‘)’ (SyntaxError) …,
element_selector, check_etag=true)
^

Thanks for any tip.

Iñaki Baz C. wrote:

Hi, I expected that the following is valid in Ruby 1.9:

def get_element(auid, document=nil, selector, check_etag=true)
[…]
end

What do you expect

get_element(1,2,3)

to do?

El Martes, 21 de Julio de 2009, Joel VanderWerf escribió:

to do?

auid = 1
document = 2
selector = 3
check_etag = true

Humm, I understand now… Having it, the second parameter “document=nil”
is
useless at all since it requires being declared anyway.

Ok, I’ve solved my problem by leaving the method as follows:

def get_element(auid, document, selector, check_etag=true)

Thanks a lot.

Iñaki Baz C. wrote:

Hi, I expected that the following is valid in Ruby 1.9:

def get_element(auid, document=nil, selector, check_etag=true)
[…]
end

However I get an error:

syntax error, unexpected ‘=’, expecting ‘)’ (SyntaxError) …,
element_selector, check_etag=true)
^

Thanks for any tip.

You couldn’t you rearrange it to?

def get_element(auid, selector, document=nil, check_etag=true)
[…]
end

El Miércoles, 22 de Julio de 2009, Joseph L. escribió:

element_selector, check_etag=true)
^

Thanks for any tip.

You couldn’t you rearrange it to?

def get_element(auid, selector, document=nil, check_etag=true)
[…]
end

Yes, I could, but I prefer to keep the order.

Iñaki Baz C. wrote:

Hi, I expected that the following is valid in Ruby 1.9:

def get_element(auid, document=nil, selector, check_etag=true)
[…]
end

However I get an error:

syntax error, unexpected ‘=’, expecting ‘)’ (SyntaxError) …,
element_selector, check_etag=true)
^

Thanks for any tip.

def get_element(auid, *rest)
case rest.size
… etc
end

Are you saying that get_element(1,2) would use auid=1 and selector=2,
but get_element(1,2,3) would use auid=1 and document=2 and selector=3?
If so it might be slightly better documented as

def get_element(auid, document_or_selector, *rest)
case rest.size
when 0
document = nil
selector = document_or_selector
check_etag = true
when 1
document = document_or_selector
selector = rest[0]
check_etag = true
when 2
document = document_or_selector
selector = rest[0]
check_etag = rest[1]
else
raise ArgumentError, “wrong number of arguments (#{rest.size}+2)”
end
… etc
end