I was going through some code I found online and found the following
def change input
('a'..'z').map { |letter| input.downcase.include?(letter) ? '1' : '0' }.join
end
I understand what this code is doing. It will take a string, check if the string contains each letter of the alphabet and return 1 if true and 0 if false.
However I am unfamiliar with this bit of syntax:
?(letter) ? '1' : '0' }
I know that a question mark is usually used to indicate that the method will return a boolean result. But I am insure why there is a second question mark after the argument.
Also, I understand that this will return 1 if true and 0 if false. Is that what this colon represents. Is it always ok to use a colon like this if the result of the method in the block will be a boolean?
The format boolean_expression ? option_a : option_b
boolean_expression ? option_a : option_b
is called a ternary operator. It is short for
if boolean_expression
option_a
else
option_b
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.