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.
The ternary operator is used to return a value based on the result of a binary condition. It takes in a binary condition as input, which makes it similar to an 'if-else' control flow block. It also, however, returns a value, behaving similar to a function.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary. You can write the above program in just 3 lines of code using a ternary operator.
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With