Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method from within itself to execute again

Tags:

ruby

recursion

What is the proper way in ruby to call a method from within itself to rerun In the sample below when @dest_reenter is equal to yes I would want the b_stage method to execute again

def b_stage 
    if @dest_reenter == 'yes'
        @dest_reenter = nil
        b_stage
    end
end
like image 272
veccy Avatar asked Aug 16 '10 20:08

veccy


People also ask

Can I call a method within itself?

Calling a function inside of itself is called recursion. It's a technique used for many applications, like in printing out the fibonacci series.

Can you call a method inside the same method?

Yes you can. It is called recursion .

Can you call a method within itself C#?

No, it is perfectly fine to call method from itself - the name is "recursion" / "recursive function".


2 Answers

That is how you do recursion, but using those instance variables isn't the way to go. A better example would be something like this:

def b_stage(i)
    if i < 5
        puts i
        i += 1
        b_stage(i)
    end
end

If you call b_stage(0), the output will be

0
1
2
3
4
like image 136
Jesse Jashinsky Avatar answered Sep 18 '22 23:09

Jesse Jashinsky


Use a separate method:

def go
  ...
  middle_thing(true)
end

def middle_thing(first_time)
  next_page unless first_time == true
  parse_page
end

def parse_page
  ...(parsing code)
  middle_thing(false)
end
like image 44
boulder_ruby Avatar answered Sep 18 '22 23:09

boulder_ruby