Reputation: 1352
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
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
foo (['path' ,nil, 'path3' ])
=>
path
def_val_2
path3
Upvotes: 0
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
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