0

Is there any way I can make ruby method that does something even if given X number of arguments and excepted more than X number of arguments?

For example:

def greet (name)
  name != nil ? "Hello, ${name}!" : "Hello!"
end

print greet()

should return "Hello!"

4 Answers4

1

Whether one wants to cover any amount of arguments, they usually use splat parameter:

def greet(*params)
  case params.size
  when 0 then "Hello!"
  when 1 then "Hello, #{params.first}!"
  else "Hello, ya all there!"
end

or:

def greet(*params)
  name, = params
  name.nil? ? "Hello!" : "Hello, #{name}!"
end
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
1

So, if you want to pass n-number of arguments, you can do it with *args (which will translate it as a list of arguments)

def test(*args)
  args.empty? "if true something" : "if false something"
end

P.S. You can read more about it here

Community
  • 1
  • 1
0

I would do:

def greet(name = nil)
  name ? "Hello, #{name}!" : "Hello!"
end

>> greet("Joe")
#⇒ "Hello, Joe!"
>> greet
#⇒ "Hello!"
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
moveson
  • 5,103
  • 1
  • 15
  • 32
0

Here's a simple method which should work any number of arguments :

def greet(*names)
  ['Hello', *names].join(', ') + '!'
end

puts greet
# Hello!
puts greet('John')
# Hello, John!
puts greet('Jane', 'John')
# Hello, Jane, John!

You could add some more logic to display "Hello, Jane, John & Jack!".

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124