Home > Back-end >  How to set a variable from an if statement with nested if statements
How to set a variable from an if statement with nested if statements

Time:07-19

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

CodePudding user response:

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"

CodePudding user response:

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