Sylar Sylar - 4 months ago 16
Ruby Question

Best way to shorten arguments passed to a method

What's the best way to pass long length of variables, as arguments, to a method?

def foo(a,b,c,d,e,f) # Could this be shorter? No?
puts f + " loves " + e
# dad loves you
end

egg = "Chicken"
girl = "Money"
car = "luxury"
rich = "poor"
me = "you"
mom = "dad"

foo(egg, girl, car, rich, me, mom)


Is there something down the lines of
foo(a..f)
? Yes, that wont work but was looking for something short and neat, if possible.

Answer

All the possible ways to call methods are described in the documentation:

egg = "Chicken"
girl = "Money"
car = "luxury"
rich = "poor"
me = "you"
mom = "dad"

Option 1. Use splat

def foo(*args)
  puts "#{args[-1]} loves #{args[-2]}"
end
foo(*[egg, girl, car, rich, me, mom])  # dad loves you

Option 2. Use double splat

def foo(**params)
  puts "#{params[:mom]} loves #{params[:me]}"
end
foo(me: me, mom: mom)  # dad loves you
double splat with defaults:
def foo(me: 'you', mom:,  **params)
  puts "#{mom} loves #{me}"
end
foo(mom: mom)  # dad loves you