Help me understand this code

Can anyone explain the syntax for the following code? It worked in rails
3.1/1.9.2 but fails to work in 2.3.4/1.8.7. It’s defined in a model if
it pertains. What’s the 1.8.7 equivalent? Many thanks.

digital? ? :digital : :real

On Sunday 28 August 2011 17:08:46 Chris R. wrote:

Can anyone explain the syntax for the following code? It worked in rails
3.1/1.9.2 but fails to work in 2.3.4/1.8.7. It’s defined in a model if
it pertains. Many thanks.

digital? ? :digital : :real

It’s a shorter form for

if digital? then :digital
else :real
end

This general form of this expression is:

a ? b : c

The part before the question mark (note that in your code the first
question
mark one is part of the method name a it has no special meaning) is the
condition; the part between the question mark and the column is the
value to
return if the condition evaluates to true and the part after the colon
is the
value to return if the condition evaluates to false.

I don’t know rails so I can’t say what has changed between rails
versions to
make it stop working. I don’t think there were changes in ruby from 1.8
to 1.9
affecting this construct. Also, what do you exactly mean by “fails to
work”?
Does it produce an error (in which case you should post the error
message to
help people understand what may be going on), or does it just give
unexpected
results?

I hope this helps

Stefano

On Sun, Aug 28, 2011 at 3:08 AM, Chris R. [email protected]
wrote:

Can anyone explain the syntax for the following code? It worked in rails
3.1/1.9.2 but fails to work in 2.3.4/1.8.7. It’s defined in a model if
it pertains. Many thanks.

digital? ? :digital : :real


Posted via http://www.ruby-forum.com/.

That’s a ternary operator, it works like Stefano said. It isn’t broken,
whatever code was using it must be broken.

On Sunday, August 28, 2011 06:41:54 AM Josh C. wrote:

That’s a ternary operator, it works like Stefano said. It isn’t broken,
whatever code was using it must be broken.

And the way we can figure that out is with an error message.

I’m surprised that programmers still do this:

“It worked in rails 3.1/1.9.2 but fails to work in 2.3.4/1.8.7.”

WTF does “worked” and “fails to work” mean in this context? Does it
crash? (If
so, is there a stacktrace?) Does it do something other than what you
expect?
Does it cause a unit test to fail? etc etc…

Perfect. Thank you