0

How can I call "multiple recursive function" in Ruby that takes the function as an argument over and over again?

By that, I don't mean the usual recursive function like fibonacci sequence. Let's say I have a function called hey(). It prints the string "Hey" as many times as the function is called within the function. To clarify:

hey() #=> "Hey "
hey(hey()) #=> "Hey Hey "
hey(hey(hey())) #=> "Hey Hey Hey "

I tried

def hey(*args)
    "Hey "
end

def hey(*args)
    "Hey " + hey(*args)
end

def hey(n)
    "Hey " + hey(n)
end

I have never seen any example like this before. I know it is doable, but not sure how. Is *args required? Do I need to pass regular argument instead of *args?

Community
  • 1
  • 1
Iggy
  • 5,129
  • 12
  • 53
  • 87

1 Answers1

5

Is this what you're looking for?

def hey(str="")
  "Hey " + str
end

p hey(hey(hey())) # "Hey Hey Hey "
user94559
  • 59,196
  • 6
  • 103
  • 103