Best ternary-operator questions in March 2012

How do you read this ternary condition in Ruby?

6 votes

I came across a ternary in some code and I am having trouble understanding the conditional:

str.split(/',\s*'/).map do |match|
  match[0] == ?, ?
    match : "some string"
end.join

I do understand that I am splitting a string at certain points and converting the total result to an array, and dealing with each element of the array in turn. Beyond that I have no idea what's going on.

A (slightly) less confusing way to write this is:

str.split(/',\s*'/).map do |match|
  if match[0] == ?,
    match
  else
    "some string"
  end
end.join

I think multiline ternary statements are horrible, especially since if blocks can return in Ruby.

Probably the most confusing thing here is the ?, which is a character literal. In Ruby 1.8 this means the ASCII value of the character (in this case 44), in Ruby 1.9 this is just a string (in this case ",").

The reason for using a character literal instead of just "," is that the return value of calling [] on a string changed in Ruby 1.9. In 1.8 it returned the ASCII value of the character at that position, in 1.9 it returns a single-character string. Using ?, here avoids having to worry about the differences in String#[] between Ruby 1.8 & 1.9.

Ultimately the conditional is just checking if the first character in match is ,, and if so it keeps the value the same, else it sets it to "some string".