How do you read this ternary state in Ruby?

I came across triple code in some code, and it's hard for me to understand the conditional:

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

I understand that I split the string at specific points and convert the final result into an array, and in turn process each element of the array. Also, I have no idea what is going on.

+6
source share
1 answer

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

+7
source

Source: https://habr.com/ru/post/910764/


All Articles