break and return in ruby, how do you use them?
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")
Best way to break and return a value
Why do you rescue
inside the pay_order
method? I'd rescue on the outer loop.
Given the following:
def method_a
10.times do |loop_a|
method_b
end
end
def method_b
5.times do |loop_b|
pay_order
end
end
def pay_order
...
end
I'd rescue inside method_a
, for example:
def method_a
10.times do |loop_a|
method_b
end
rescue Stripe::CardError => e
# do whatever. no need to break
end
All the loops are "broken" automatically by the raising of the exception.
If you want to do something with the exception inside the pay_order method, then I would suggest to rescue and raise again:
def pay_order
order.pay
rescue Stripe::CardError => e
# do your stuff
raise e
end
How can I return something early from a block?
next
inside a block returns from the block. break
inside a block returns from the function that yielded to the block. For each
this means that break
exits the loop and next
jumps to the next iteration of the loop (thus the names). You can return values with next value
and break value
.
How to break out from a ruby block?
Use the keyword next
. If you do not want to continue to the next item, use break
.
When next
is used within a block, it causes the block to exit immediately, returning control to the iterator method, which may then begin a new iteration by invoking the block again:
f.each do |line| # Iterate over the lines in file f
next if line[0,1] == "#" # If this line is a comment, go to the next
puts eval(line)
end
When used in a block, break
transfers control out of the block, out of the iterator that invoked the block, and to the first expression following the invocation of the iterator:
f.each do |line| # Iterate over the lines in file f
break if line == "quit\n" # If this break statement is executed...
puts eval(line)
end
puts "Good bye" # ...then control is transferred here
And finally, the usage of return
in a block:
return
always causes the enclosing method to return, regardless of how deeply nested within blocks it is (except in the case of lambdas):
def find(array, target)
array.each_with_index do |element,index|
return index if (element == target) # return from find
end
nil # If we didn't find the element, return nil
end
In Ruby, what is the return value in a loop?
the return of a loop (loop
, while
, until
, etc) can be anything you send to break
def get_action
loop do
action = gets.chomp
break action if Guide::Config.actions.include?(action)
end
end
or
def get_action
while action = gets.chomp
break action if Guide::Config.actions.include?(action)
end
end
or you can use begin .. while
def get_action
begin
action = gets.chomp
end while Guide::Config.actions.include?(action)
action
end
or even shorter
def get_action
action = gets.chomp while Guide::Config.actions.include?(action)
action
end
PS: loops themselves return nil as a result (implicit break
which is break nil
) unless you use explicit break "something"
. If you want to assign result of the loop you should use break
for this: x = loop do break 1; end
Are `return` and `break` useless inside a Ruby block when used as a callback?
Actually it's kind of interesting...
When you use before_create in Rails 3, we take the block or lambda that you give us and convert it into a method. We then invoke the method with the current ActiveRecord object, for backwards compatibility with the old Rails approach.
As a result, the following is equivalent to your snippet:
class User < ActiveRecord::Base
validates_presence_of :login, :email
before_create do
self.name = login.capitalize if name.blank?
end
end
Because of this behavior, you can call return from the block, and it will behave the same as a return in a normal method (because it is a normal method).
In general, continue
in a block "returns" from the block.
The specific behavior of normal blocks is:
- When you call
continue
, you are skipping the rest of the block, and returning control to the method that invoked the block. - When you call
break
, you are skipping the rest of the block, and also immediately returning from the method that invoked the block.
You can see that behavior in normal iterators:
value = [1,2,3,4].each do |i|
continue if i == 2
puts i
end
In this case, value
will be [1,2,3,4]
, the normal return value of the each
method, and the output will be:
1
3
4
In the case of break:
value = [1,2,3,4].each do |i|
break if i == 2
puts i
end
In this case, the value
will be nil
, since the break
also immediately returned from the each
method. You can force a return with a specific value by using break n
, which will make value
the same as n
. The output in the above case will be:
1
The important thing is that continue
and break
do not just apply to iterators, although their semantics are designed to behave like their equivalents in C in the case of iterators.
What does break do in this ruby statement
break argument
in a block causes the block to return argument
. By default, tap
returns the same object as it is given, but the break will instead cause it to return whatever o.send(version) if version
evaluates to.
Related Topics
How to Fix a Deadlock Caused by Open
How to Generate a Random Number Between a and B in Ruby
Rails Mapping Array of Hashes Onto Single Hash
Installing the Postgresql Gem with 'Gem Pq' Fails with Error: Failed to Build Gem Native Extension
Can Someone Explain Ruby's Use of Pipe Characters in a Block
Reraise (Same Exception) After Catching an Exception in Ruby
Preferred Way to Private Messages Modeling in Rails 3
How to Authorize a Service Account for Google Calendar API in Ruby
How to Input Integer Value to an Array, Based Preceeding Row + Column Values
How to Specify Local .Gem Files in My Gemfile
Ruby - Elegantly Convert Variable to an Array If Not an Array Already
If String Is Empty Then Return Some Default Value
Break and Return in Ruby, How to Use Them