Ruby ternary operator

If I do the following:

value=“off”
p value == “on” ? “YES” : “NO”
p value

Then I get the

“NO”, “off”

Does anyone know how I assign the result of the statement to a variable.
e.g the result of:

value=“off”
value == “on” ? “YES” : “NO”

“NO”

On Thursday 10 February 2011 23:12:06 Sam T. wrote:

Does anyone know how I assign the result of the statement to a variable.
e.g the result of:

value=“off”
value == “on” ? “YES” : “NO”

“NO”

Have you tried a simple assignment?

value=“off”
other_value = value == “on” ? “YES” : “NO”
puts other_value
=> “NO”

Stefano

RESOLVED: Perfect!..

On Thu, Feb 10, 2011 at 7:26 AM, Sam T. [email protected]
wrote:

RESOLVED: Perfect!..

When in doubt, fire up irb and just try something. You’ll probably
figure out the answer you were looking for in less time than it takes
to write an email and wait for a response, and I guarantee that you
will learn more in the process.

I’ve been doing Ruby for more than 9 years, and I still have an irb
session running most of the time. It is an invaluable tool.

Kirk H.

Sam T. wrote in post #980819:

If I do the following:

value=“off”
p value == “on” ? “YES” : “NO”
p value

Then I get the

“NO”, “off”

Does anyone know how I assign the result of the statement to a variable.
e.g the result of:

value=“off”
value == “on” ? “YES” : “NO”

“NO”

do you really need the “YES” and “NO”?
Why not just assign the other_value to true or false?

i.e. other_value = (value==“on”)

Then you are dealing with booleans which are less prone to error imho.

Thanks for all of the comments. Yes Bool is a potential (although the
orig mail was with simplified test data). My irb wasn’t too far away,
but I just got into the ternary operation and thought, hmm I’m not sure
how to do that!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs