0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

遅延初期化にbegin式を利用して複数行の評価値を代入する

Posted at
def hoge
  @hoge ||= "一つの式"
end

インスタンス変数の遅延初期化に良く利用される書き方だが、代入したいものが一つの式で書けない場合もある。
複数の式(複数行)の場合は次のようになると思う。

def hoge
  return @hoge if @hoge

  foo = hogehoge
  @hoge = foo * fugafuga
end

begin式を利用すれば次のように書ける。

def hoge
  @hoge ||= begin
    foo = hogehoge
    foo * fugafuga
  end
end
0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?