A (slightly) less confusing way to spell this:
str.split(/',\s*'/).map do |match| if match[0] == ?, match else "some string" end end.join
I think multiline ternary statements are terrible, especially if
blocks can be returned in Ruby.
Probably the most confusing here is ?,
Which is a character literal. In Ruby 1.8, this means the value of an ASCII character (in this case, 44
), in Ruby 1.9 it is just a string (in this case, ","
).
The reason for using a character literal instead of just a ","
is because the return value of the []
call in the string changed in Ruby 1.9. In 1.8, he returned the value of the ASCII character at this position ; in 1.9, he returns a string with one character . Using ?,
Here allows you to not worry about the differences in String#[]
between Ruby 1.8 and 1.9.
Ultimately, the conditional expression simply checks to see if the first character is in match
,
and if so, it stores the value the same way, otherwise it sets it to "some string"
.
source share