Monday, February 11, 2008

An Interrogative Statement, times 4

So I'm building a URL and the base comes from a config file where I don't know whether it's coming in with parameters.  I want to add some parameters, so I need to know if my separator should be ? or &.  I'm not doing anything fancy, just a quick string concat.  Here's how the statement came out, I thought it was funny:

 

separator = base.include?("?") ? "&" : "?"

:)!

2 comments:

Anonymous said...

I assume that base.include is a method on the string named "base" that tests whether the string includes the question mark parameter.

But what does the question mark between the method name and the parenthesis do?

Duane said...

Ruby syntax allows special characters like ? and ! to appear in method names. By convention, boolean methods (that return true or false) tend to be named with a question mark, as if asking a question. so the actual method name is base.include?("?") asking "True or false, does the base variable contain the question mark string?"

The one in the middle is a shorthand conditional. Several languages have this. Instead of saying this:

if (condition) { x=y; } else { x=z; }

you can say x = condition ? y : z

which means the same thing, "Set X conditionally to either Y or Z, depending on the condition."

Hope that answers your questions.