yield_self でチェーンをブレイクする方法
概要
Rubyでyield_self(当時)チェーンを壊すことは可能ですか?
"a".then { |str| <break> if break_condition }.then { |str| str << "b" } # => I need "a"
解決策
コード全体を別のメソッドに移動し、単純な return でチェーンを「切断」することもできます。
def foo
"a".then { |str| return str if break_condition ; str }
.then { |str| str << "b" }
end
キャッチアンドスローを利用できます。
catch do |brk|
"a".then { |str| throw(brk, str) if break_condition ; str }
.then { |str| str << "b" }
end
あるいは、そもそも then を使用できませんでした。
str = "a"
str << "b" unless break_condition