Richard_G
Richard_G

Reputation: 4820

Ruby Rails "if" with condition of "false" actually executes?

I really don't know what I am not seeing here, because it looks to me that "if false" is acting like "if true". To make it clear, I actually took screenshots of my RubyMine 6.0.3 screens. This one is probably simple, but it surely looks crazy to me...

The code is in DevicesController#update. It has a breakpoint that occurs within an "if false" statement that shouldn't be executing. See in this shot that I am on line 48 within the if: enter image description here

The variable dump at this time follows, that shows that params[:device][:chg_pwd], the if condition, is false.
enter image description here

So, why am I within this if statement when its condition is false?

Upvotes: 2

Views: 2393

Answers (3)

Karthik T
Karthik T

Reputation: 31952

"false" is true in ruby. you want == "true"

In Ruby, only nil and false are false. For more, you can read this gist

if params[:device][:chg_pwd] == "true"

Depending on your situation, the other options are

  1. Set to nil, or false. Then your existing code would work.
  2. Set to "" and check with blank? as a previous version of RSB's answer used to say, this is Rails only though, and does involve a small semantic difference (blank vs false)

Upvotes: 5

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Use this instead of "false" as "false" is a string and not a boolean value in your code

if params[:devise][:chg_pwd].eql?("false")
  # code
else
  # code
end

This would explain it better

2.0.0p247 :012 > if "true"
2.0.0p247 :013?>   p "hello"
2.0.0p247 :014?>   end
"hello"
 => "hello" 
2.0.0p247 :015 > if "false"
2.0.0p247 :016?>   p "hi"
2.0.0p247 :017?>   end
"hi"
 => "hi" 

Upvotes: 1

Bachan Smruty
Bachan Smruty

Reputation: 5734

It returns "false", which is a string, so it returns true.

if params['is_admin'] == 'true'
# YOUR CODE goes HERE
end

Upvotes: 2

Related Questions