1

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
2
  • 1
    I just ran it, a is nil in both cases, what makes you think it is assigned "domain"? Commented Jul 19, 2022 at 3:15
  • but here a returns "domain" – that's the same code with an additional puts. Ruby does not time travel. Printing a.class afterwards won't change the result of the if statement. Double check the actual code you are running. Commented Jul 19, 2022 at 10:11

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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"

2 Comments

What's with the catch-all rescue?
Isn't the ternary operator better suited on the last step?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.