🖥

#Ruby の then / yield_self は メソッドチェーンで nil を防止するための初期値代入にも使えそうだけど?

に公開

Ruby's then / yield_self could also be used for initial value assignment to prevent nil in the method chain?

題材は多分不適切

こんなので nil を防ぎたい時

numbers = [1,2,3]; numbers&.max.yield_self { |max| max || 0 } + 1
# => 4

then / yield_self での書き方

numbers = nil; numbers.then { |numbers| numbers || [] }.max.then { |max| max || 0 } + 1
# => 1

numbers = nil; numbers.yield_self { |numbers| numbers || [] }.max.yield_self { |max| max || 0 } + 1
# => 1

かっこでくくる + ぼっち演算子での書き方

numbers = nil; (numbers&.max || 0) + 1
# => 1

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2254

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2019-07-07

Discussion