Richard Fairhurst
Richard Fairhurst

Reputation: 814

Passing a default value to a Ruby method, one level deep

If I have the following Ruby code:

def result(b=25)
  puts b
end

then I can simply call result, and 25 will be output. So far, no problem.

But I'd like to call it from another method, like this:

def outer(a,b)
  #...do some stuff with a...
  result(b)
end

and I'd like outer(1,5) to output 5, but outer(1) to simply output 25. In effect, I want to pass "undefined" through to the result method.

Is there any way I can do this? (I can't simply use def outer(a,b=25), sadly, because the default value for b is actually an instance variable of the class in which result is a method.)

Upvotes: 0

Views: 3474

Answers (3)

Iuri G.
Iuri G.

Reputation: 10630

what about this:

def outer(a,b = nil)
  ...do some stuff with a...
  result(*[b].compact)
end

That will call result(b) if b is not nil and result() if b is nil

Upvotes: 2

Raj
Raj

Reputation: 1784

My proposed solution changes your initial problem just a tiny bit, but it's close. You can default the second value of outer with the inner method, and then call the inner method again. It works a bit strangely if you are actually outputting something, but if you don't call puts, it works pretty well.

def result(b=25)
  b
end

def outer(a, b = result)
  #...do stuff with a...
  puts result(b)
end

This will assign the default to b only if you don't provide it. If you do provide it, it will then use that b in result. Functionally it seems to work the way you want it, the only caveat is that if your inner method were doing something non-trivial, you would be duplicating the work in the default case.

Upvotes: 0

Erez Rabih
Erez Rabih

Reputation: 15788

An option to solve this would be to put b behind a getter method:

def get_b
  @b
end

def outer(a, b = get_b)
  #...do some stuff with a...
  result(b)
end

Upvotes: 0

Related Questions