ここは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
end
そしてここにあります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
end
raise を使うことも考えましたが、汎用的にしようとしているので、 に具体的なものを入れたくありませんFoo
。
ベストアンサー1
キーワード を使用しますnext
。次の項目に進まない場合は を使用しますbreak
。
next
をブロック内で使用すると、ブロックは直ちに終了し、制御がイテレータ メソッドに戻ります。その後、ブロックを再度呼び出すことで新しい反復処理を開始できます。
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
ブロック内で使用すると、break
制御がブロックの外、ブロックを呼び出した反復子の外、反復子の呼び出しに続く最初の式に移ります。
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
return
最後に、ブロック内での使用法です。
return
ブロック内でどれだけ深くネストされているかに関係なく、常に囲んでいるメソッドが返されます (ラムダの場合を除く)。
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