0

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!

falsetru
  • 357,413
  • 63
  • 732
  • 636
Sherwyn Goh
  • 1,352
  • 1
  • 10
  • 19

3 Answers3

2

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
vee
  • 38,255
  • 7
  • 74
  • 78
1

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

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
AlexFink
  • 41
  • 4