Ruby ternary operator

S

Sam T.

If I do the following:

value="off"
p value == "on" ? "YES" : "NO"
p value

Then I get the
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"
 
S

Stefano Crocco

If I do the following:

value="off"
p value == "on" ? "YES" : "NO"
p value

Then I get the


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"

Have you tried a simple assignment?

value="off"
other_value = value == "on" ? "YES" : "NO"
puts other_value
=> "NO"

Stefano
 
K

Kirk Haines

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 Haines
 
P

Paul Mckibbin

Sam T. wrote in post #980819:
If I do the following:

value="off"
p value == "on" ? "YES" : "NO"
p value

Then I get the

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"

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.
 
S

Sam T.

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,139
Messages
2,570,807
Members
47,356
Latest member
Tommyhotly

Latest Threads

Top