Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to break chain with yield_self

Tags:

ruby

Is it possible to break yield_self (then) chain in ruby?

"a".then { |str| <break> if break_condition }.then { |str| str << "b" } # => I need "a"
like image 667
gayavat Avatar asked Oct 22 '25 11:10

gayavat


1 Answers

You could move the whole code into another method and "break" the chain with a simple return:

def foo
  "a".then { |str| return str if break_condition ; str }
     .then { |str| str << "b" }
end

You could utilize catch and throw:

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

Alternatively, you could not use then in the first place:

str = "a"
str << "b" unless break_condition
like image 143
Stefan Avatar answered Oct 25 '25 12:10

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!