6

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.

1 Answer 1

7

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

3
  • Thanks @AndrewMarshall, it would have helped if it was match == ( ?, ) ? match : "some string" ? Or would that mean something else?
    – ismail
    Commented Mar 15, 2012 at 2:35
  • @IsmailTabtabai That would be the same. Whenever I do ternary statements I usually wrap the whole conditional statement in parenthesis to make it clear where it is, but that's just style. Character literals are probably one of the lesser-known syntactic structures of Ruby, and can be very confusing when you don't know what it is (especially when paired with other ?s). Commented Mar 15, 2012 at 2:39
  • It means the same thing. So would match[0] == ?, ? match : "some string"
    – Bijan
    Commented Mar 15, 2012 at 2:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.