Sherwyn Goh
Sherwyn Goh

Reputation: 1352

How do I define a method that can accept 2 arguments but can function with just 1, with a default value for the other?

short example.

def yay(a, b = "1")
value  = a + b
return value
end

I would like to be able to do this

something.yay(2)

and get 3 returned, and also do this

something.yay(2,3)

and get 5.

Thanks in advance!

Upvotes: 0

Views: 85

Answers (3)

AlexFink
AlexFink

Reputation: 41

I found the following useful for general purpose of this sort:

def foo(*a)
  ## define default vals
  params = {'param1_name' => 'def_val_1','param2_name' => 
'def_val_2','param3_name' => 'def_val_3'}
  params.each_with_index do |(key_,val_), ind_|
    params[key_] = ( a.first[ind_].nil? ? val_ : a.first[ind_])
    puts params[key_]
  end

end

when calling function put nil if you desire a default val

foo (['path' ,nil, 'path3' ])
=>
path
def_val_2
path3

Upvotes: 0

falsetru
falsetru

Reputation: 369064

Use Fixnum literal, instead of string literal:

class Something
  def yay(a, b = 1) # <----
    a + b # You don't need `return`: the last value evaluated is returned.
  end
end
something = Something.new
something.yay(2)
# => 3
something.yay(2, 3)
# => 5

Upvotes: 1

vee
vee

Reputation: 38645

You already have it right, the only problem I suppose is the data type.

Try:

def yay(a, b = 1)
  a + b
end

Or if this method is to operate only on integer types you could cast both parameters to integer using to_i as:

def yay(a, b = "1")
  a.to_i + b.to_i
end

Upvotes: 2

Related Questions