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

2018-12-31 03:04发布

What does the following code mean in Ruby?

||=

Does it have any meaning or reason for the syntax?

20条回答
梦醉为红颜
2楼-- · 2018-12-31 03:37

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.

查看更多
明月照影归
3楼-- · 2018-12-31 03:39
irb(main):001:0> a = 1
=> 1
irb(main):002:0> a ||= 2
=> 1

Because a was already set to 1

irb(main):003:0> a = nil
=> nil
irb(main):004:0> a ||= 2
=> 2

Because a was nil

查看更多
登录 后发表回答