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