What does ||= (or-equals) mean in Ruby?

前端 未结 23 2884
情书的邮戳
情书的邮戳 2020-11-21 23:20

What does the following code mean in Ruby?

||=

Does it have any meaning or reason for the syntax?

23条回答
  •  无人共我
    2020-11-21 23:40

    It means or-equals to. It checks to see if the value on the left is defined, then use that. If it's not, use the value on the right. You can use it in Rails to cache instance variables in models.

    A quick Rails-based example, where we create a function to fetch the currently logged in user:

    class User > ActiveRecord::Base
    
      def current_user
        @current_user ||= User.find_by_id(session[:user_id])
      end
    
    end
    

    It checks to see if the @current_user instance variable is set. If it is, it will return it, thereby saving a database call. If it's not set however, we make the call and then set the @current_user variable to that. It's a really simple caching technique but is great for when you're fetching the same instance variable across the application multiple times.

提交回复
热议问题