snippetrubyCritical
How to break out from a ruby block?
Viewed 0 times
howfromrubyblockbreakout
Problem
Here is
And here is
I thought about using raise, but I am trying to make it generic, so I don't want to put anything any specific in
Bar#do_things:class Bar
def do_things
Foo.some_method(x) do |x|
y = x.do_something
return y_is_bad if y.bad? # how do i tell it to stop and return do_things?
y.do_something_else
end
keep_doing_more_things
end
endAnd here is
Foo#some_method: class Foo
def self.some_method(targets, &block)
targets.each do |target|
begin
r = yield(target)
rescue
failed << target
end
end
end
endI thought about using raise, but I am trying to make it generic, so I don't want to put anything any specific in
Foo.Solution
Use the keyword
When
When used in a block,
And finally, the usage of
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)
endWhen 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 hereAnd 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
endCode Snippets
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)
endf.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 heredef 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
endContext
Stack Overflow Q#1402757, score: 813
Revisions (0)
No revisions yet.