Iggy
Iggy

Reputation: 5251

Ruby recursion calling its own function as argument

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?

Upvotes: 0

Views: 52

Answers (1)

user94559
user94559

Reputation: 60153

Is this what you're looking for?

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

p hey(hey(hey())) # "Hey Hey Hey "

Upvotes: 5

Related Questions