Why does single `=` work in `if` statement?

后端 未结 4 1225
囚心锁ツ
囚心锁ツ 2021-01-18 02:28

This code is provided as an example in for use with devise and OmniAuth, it works in my project.

class User < ActiveRecord::Base
  def self.new_with_sessi         


        
4条回答
  •  渐次进展
    2021-01-18 03:23

    In Ruby, a single equals sign is used for assignment. The expression

    data = session["devise.facebook_data"]
    

    assigns the result of evaluating session["devise.facebook_data"] to a local variable named data.

    If the session hash doesn't have a "devise.facebook_data" key, it will return nil and data will be assigned nil. Assignments evaluate to the value being assigned, so the assignment will evaluate to nil as well. nil is considered falsey in a boolean context, so the right operand of the && will not be evaluated. That way, you won't get a NoMethodError trying to call nil["extra"]["raw_info"].

    If the session hash does have a "devise.facebook_data" key, data will be set to the value associated with it. Any value other than nil and false is considered truthy, therefore the right-hand operand of the && operator will be evaluated.

    If the condition is truthy, the then clause will be evaluated, which uses the data variable assigned in the condition.


    Note: I believe one could also use the data variable within the right-hand side of the && operator, i.e. the condition could read like this instead:

    if data = session["devise.facebook_data"] && data["extra"]["raw_info"]
    

    But I'll have to check that.

提交回复
热议问题