为什么单个 `=` 在 `if` 语句中起作用? [英] Why does single `=` work in `if` statement?

查看:47
本文介绍了为什么单个 `=` 在 `if` 语句中起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码作为用于设计和 OmniAuth 的示例提供,它适用于 我的项目.

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_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end
end

我不知道为什么它是与双等号并列的单个等号,我认为这对于 if 语句是必要的.我的 IDEintelliJ IDEA"同意我的担忧.

I don't know why it's a single equals sign as apposed to a double equals sign, which I thought was necessary for if-statements. My IDE "intelliJ IDEA" agrees with my concerns.

推荐答案

使 if 语句有效的唯一必要条件是布尔表达式.在这种情况下,由于 = 返回赋值的结果,因此实际测试的是 session["devise.facebook_data"] 的虚假性.

The only necessary thing for an if statement to be valid is a boolean expression. In this case, since = returns the result of the assignment, what's actually being tested is the falsiness of session["devise.facebook_data"].

IntelliJ 对这样的代码提出投诉是一个很好的观点,因为如果不了解 Ruby 的一两件事就很难阅读.建议将其移至显式赋值语句.这有一个额外的好处,就是对它的引用进行两次干燥.

IntelliJ has a good point to lodge a complaint about code like this, as it's difficult to read without knowing a thing or two about Ruby. A recommendation would be to move that to an explicit assignment statement instead. This has the added benefit of DRYing up a reference to it twice.

class User < ActiveRecord::Base
  def self.new_with_session(params, session)
    super.tap do |user|
      data = session["devise.facebook_data"]
      if data && data["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end
end

这篇关于为什么单个 `=` 在 `if` 语句中起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆