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
Ruby syntax: break out from 'each.. do..' block
You can break with the break
keyword. For example
[1,2,3].each do |i|
puts i
break
end
will output 1
. Or if you want to directly return the value, use return
.
Since you updated the question, here the code:
class Car < ActiveRecord::Base
# …
def self.check(name)
self.all.each do |car|
return car if some_condition_met?(car)
end
puts "outside the each block."
end
end
Though you can also use Array#detect
or Array#any?
for that purpose.
Break out of a begin/end block early
I think you're going to save yourself a whole heck of a lot of strife if you just put all that logic into its own method:
def foo
@foo ||= compute_foo
end
def compute_foo
puts "running"
return "leaving early" if true # would be some sort of calculation
# Other calculations
end
This decouples the computation from the memoization, making it easier to test and reason about, and it's a fairly common design pattern in Ruby and other languages.
Of course, there are ways of doing what you're asking. The most obvious solution being an immediately-invoked anonymous proc:
def foo
@foo ||= (proc do
puts "running"
next "leaving early" if true # would be some sort of calculation
# Other calculations
end)[] # or .call or .()
end
But you certainly wouldn't be doing yourself or any future maintainers of this code any favors.
How to break out of begin block in Ruby?
Well, you could raise an error. That's how begin/rescue blocks work. It's not a good idea, though - using error handling for business logic is generally frowned upon.
It seems as though it would make much more sense to refactor as a simple conditional. Something like:
def function
@document = Invoice.find_by(:token => params[:id])
if @document.sent_at < 3.days.ago
flash[:error] = "Document has expired."
redirect_to root_path
else
@document.mark_as_viewed
end
end
It seems as though you've confused a few different kinds of block-related keywords here:
Error handling (begin
/rescue
/end
) is for cases where you think something you try might raise an error, and respond in a particular way to it.
next
is for iteration - when you're looping through a collection and want to skip to the next element.
Conditionals (if
, unless
, else
, etc.) are the usual way for checking the state of something and executing different bits of code depending on it.
How to break out of case statement in Ruby
If that is all you have in the method body, then just do return
instead of break
.
If you cannot do that, then do:
when 1
unless <already executed for some similar data>
#Some code
end
when 2
...
Break out a loop from within a (yielded) block inside the loop
One way is to use throw/catch
. No, not exceptions, Ruby has a separate control-of-flow feature that works a bit like exceptions, without all the overhead (although I must admit I'm not sure that there isn't any overhead in using it):
catch :stop_all_jobs do
msg job.name do
throw :stop_all_jobs if stop_all_jobs?
job.run!
end
end
You can even pass a value as the second argument to throw
which will be the result of the catch
block.
A potentially more readable solution would, of course, be to pack the code up in a method and use return
in place of break
. But that wouldn't be as fun.
Break out of conditional block in rails
You can use break
<% @projects.each_with_index do |project, index| %>
<% break if index < 5 %>
<% end %>
--
Or you could also use .take
as per this answer:
<% @projects.take(5).each do |project| %>
...
<% end %>
This will allow you limit the value of the loop to 5 objects only, preventing the need for further logic
break
is a common programming function, designed to get out of a loop
What Dax
and I were suggesting was to add it along-side your if
statement:
<% if index < 5 %>
<% break %>
<% else %>
... do something
<% end %>
If you just want to add an icon for the first 5 links, you'll want to do this:
<% your_class = index > 5 ? nil : "icon_class" %>
<%= link_to "path", path_helper, class: your_class %>
--
Update
In response to your pastie, here's what you need to do:
<div class="row sub-navigation">
<% @projects.each_with_index do |project, index| %>
<div class="col-sm-2 col-xs-1">
<% your_class = index > 5? "icon_class" : nil %>
<% link_to "", path, remote: true, id: "project_div", class: your_class %>
</div>
</div>
How to break or stop ruby_block running in loop cause of subscribes
Make a custom resource instead, you want more explicit control over things than the DSL will give you.
Related Topics
Difference Between Require_Relative and Require in Ruby
Getting Output of System() Calls in Ruby
The Authorization Mechanism You Have Provided Is Not Supported. Please Use Aws4-Hmac-Sha256
Class ≪≪ Self Idiom in Ruby
Ruby, Difference Between Exec, System and %X() or Backticks
How to Change Default Timezone For Active Record in Rails
Can't Install Ruby Under Lion With Rvm - Gcc Issues
Difference Between Attr_Accessor and Attr_Accessible
How to Prevent Browser Page Caching in Rails
How to Avoid Nomethoderror For Missing Elements in Nested Hashes, Without Repeated Nil Checks
How to Sort an Array in Descending Order in Ruby
Code Block Passed to Each Works With Brackets But Not With 'Do'-'End' (Ruby)
Bundle Install Fails With Ssl Certificate Verification Error
Is 'Eval' Supposed to Be Nasty
Pg::Connectionbad - Could Not Connect to Server: Connection Refused