Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break and return in ruby, how do you use them?

Tags:

return

ruby

break

I just asked a question about return and it seems to do the same thing as break. How do you use return, and how do you use break, such as in the actual code that you write to solve the problems that can use these constructs.

I can't really post examples because I don't know how to use these so they wouldn't make much sense.

like image 471
thenengah Avatar asked Jan 05 '11 07:01

thenengah


People also ask

How do you use break in Ruby?

In Ruby, we use a break statement to break the execution of the loop in the program. It is mostly used in while loop, where value is printed till the condition, is true, then break statement terminates the loop. In examples, break statement used with if statement. By using break statement the execution will be stopped.

How do returns work in Ruby?

Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.

Does Ruby have return statement?

Ruby return StatementThe return statement in ruby is used to return one or more values from a Ruby Method.

How do you exit a block in Ruby?

To break out from a ruby block simply use return keyword return if value.


1 Answers

Return exits from the entire function.

Break exits from the innermost loop.

Thus, in a function like so:

def testing(target, method)   (0..100).each do |x|     (0..100).each do |y|      puts x*y      if x*y == target        break if method == "break"        return if method == "return"      end     end    end end 

To see the difference, try:

testing(50, "break") testing(50, "return") 
like image 115
stef Avatar answered Oct 10 '22 10:10

stef