Default method parameters

Hello

I have an method like this:
def test(x, y=’’, z=’’)
puts “x=#{x} y=#{y} z=#{z}”
end

and I want call with x and z parameters:
test(‘x’, z=‘z’)
output:
x=‘x’ y=‘z’ z=’’

How you can see, the Z value appears in Y parameter…
and I want call just with X and Z parameters

Thanks a lot!

Cassiano R.
RS - Brazil

This is a ruby question rather than a rails question.
Anyway, ruby doesn’t have named parameters, you you just can’t do that.
You’re passing z=‘z’ as the second argument, which evaluates to ‘z’ and
so y is set to ‘z’.
With ruby’s default arguments stuff you must pass in the leftmost n
parameters, for some value of n. (ie no ‘gaps’)

Fred

You can always simulate it by passing in a hash:

def test(in_hsh={})
puts “x=#{in_hsh[‘x’]} y=#{in_hsh[‘y’]} z=#{in_hsh[‘z’]}”
end

test({‘x’ => ‘x’, ‘z’ => ‘z’)

Cassiano R. wrote:

x=‘x’ y=‘z’ z=’’


Sincerely,

William P.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs