简体   繁体   English

Ruby Block语法

[英]Ruby Block syntax

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. 它将使用一个字符串,检查该字符串是否包含字母表中的每个字母,如果为true,则返回1,如果为false,则返回0。

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. 另外,我知道如果为true,则返回1,如果为false,则返回0。 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 boolean_expression ? option_a : option_b is called a ternary operator. boolean_expression ? option_a : option_b称为三元运算符。 It is short for 它的缩写

if boolean_expression
  option_a
else
  option_b
end

The first question mark is part of the #include? 第一个问号是#include吗? method 方法

The expession condition ? if_true : if_false 使用condition ? if_true : if_false condition ? if_true : if_false is called a ternary operator, which is shorthand for condition ? if_true : if_false称为三元运算符,是三元运算符的简写

if condition
  if_true
else
  if_false
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM