Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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.

like image 739
thesowismine Avatar asked Jun 10 '15 22:06

thesowismine


People also ask

Why is my else statement not working Java?

If you are getting an error about the else it is because you've told the interpreter that the ; was the end of your if statement so when it finds the else a few lines later it starts complaining. A few examples of where not to put a semicolon: if (age < 18); if ( 9 > 10 ); if ("Yogi Bear".

How does the if statement work?

The IF statement works by checking the expression to see whether a condition is met and returns a value based on the output obtained. For example, based on the criteria, it returns one predetermined value if the condition is found to be true and a different predefined value if the statement is found to be false.

How do you write an if statement with condition?

OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)

Which statement allows you to check a secondary condition if the first condition is false?

The else statement If we want our programs to execute a different set of instructions when the condition is false, then we can use an else statement.


1 Answers

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 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
like image 100
Makoto Avatar answered Sep 19 '22 20:09

Makoto