thiebo
thiebo

Reputation: 1435

ruby optionnal argument unexpected *

I have this very simple piece of code (using Ruby 3)

def eat(main, dessert*)
  if dessert.empty?
    puts "I eat #{main}"
  else
    puts "I eat #{main} than #{dessert}."
  end
end

Wher I run eat("mushrooms") that provokes errors:

argu.rb:1: syntax error, unexpected '*', expecting ')'
def manger(plat, dessert*)
argu.rb:7: syntax error, unexpected `end', expecting end-of-input

I don't see why.

Upvotes: 1

Views: 46

Answers (2)

user1934428
user1934428

Reputation: 22225

Not sure where you got the idea from using dessert*, but you could define your method as

def eat(main, dessert = [])

to provide a default argument (of course it must be one which can respond to empty?).

Of course it is up to you to justify, why "main" can be anything (i.e. a String), but dessert must be a collection. I would test for dessert as

if dessert.nil?

and hence provide nil as default value for the dessert.

Upvotes: 1

whilrun
whilrun

Reputation: 1724

Splat operator should put before parameters so your signature should be

def eat(main, *dessert)

Upvotes: 3

Related Questions