How to set a variable from an if statement with nested if statements

Viewed 70

Can someone explain why the variable a is nil?

a = if true
    "domain" if true
    "nilr" if nil
end

but here a returns "domain"

a = if true
    "domain" if true
    "nilr" if nil
end

puts a.class
5 Answers

Ruby evaluates each element of the block and returns, implicitly, the result of last statement to run. In this case it's the if nil test, which is going to fail, and hence, return nil.

Your code, simplified, looks to Ruby like:

a = begin
    "domain"
    nil
end

Where that block has a nil at the end, hence evaluates to nil.

If you want to branch:

a = if true
  if false
    "domain"
  elsif nil
    "nilr"
  end
end

Though this code is still pretty pointless since without an expression on your if that changes the result will always be the same.

What you might be intending is actually something like this:

a = case x
 when true
   "domain"
 when nil
  "nilr"
 end

Where a will take on different values depending on what x is.

You don't have a value to check domain or nilr so when run

Step 1:

a = if true
    "domain" if true
end
=> result: a = "domain"

Step 2: if nil is runing

a = if true
    "domain" if true
    "nilr" if nil
end
=> result: a = "nilr"

Step 3: return a = "nilr"

Solution: You should use a other params EX: is_domain, env ...

a = is_domain? "domain" rescue "nilr"

Unexecuted if statement returns nil.

Yeah in the first if statement the nil get assigned because it cannot be evaluated.

It does not return "domain". There is no return method in that line. The thing is, Ruby runs the last line and returns its results and for that if the last line is:

"nilr" if nil

And the result of that line is nil, if it was:

"nilr" if true

"a" would be "nilf".

You can check running that line alone and see the result.

To set a variable using an if statement you can do something like this:

a = if false
  "domain"
elsif true
  "nilr"
end
Related