LoginSignup
0
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2019-07-07

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

チャットメンバー募集

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

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0