如何用yield_self打破链条

gay*_*vat 4 ruby

是否有可能打破 ruby​​ 中的 Yield_self (then) 链?

"a".then { |str| <break> if break_condition }.then { |str| str << "b" } # => I need "a"
Run Code Online (Sandbox Code Playgroud)

Ste*_*fan 6

您可以将整个代码移至另一个方法中,并通过简单的操作“打破”链条return

def foo
  "a".then { |str| return str if break_condition ; str }
     .then { |str| str << "b" }
end
Run Code Online (Sandbox Code Playgroud)

您可以利用catchthrow

catch do |brk|
  "a".then { |str| throw(brk, str) if break_condition ; str }
     .then { |str| str << "b" }
end
Run Code Online (Sandbox Code Playgroud)

then或者,您一开始就不能使用:

str = "a"
str << "b" unless break_condition
Run Code Online (Sandbox Code Playgroud)