10
5

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 current_user
  @current_user ||= User.find(session[:id])
end

ところで、ユーザーを見つけるロジックがもっと複雑で、複数行に渡って書ける場合はどう書けばいいのでしょうか。

ここでbeginの出番です。rescueとのセットで有名ですが、実はrescueなしでも使えます。

def current_user
  @current_user ||= begin
                      some_complex_logic
                      to_fetch
                      user
                    end
end

この場合、最後のuserが評価されて@current_userに代入されることになります。

10
5
7

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
10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?