这个| _在Ruby中是什么意思?

时间:2021-04-08 16:36:57

In this code:

在这段代码中:

arr.select.each_with_index { |_, i| i.even? }

what does pipe underscore mean?

管道下划线是什么意思?

3 个解决方案

#1


7  

_ is a variable name like every other variable name (for example i). It is a convention in Ruby to use _ as a variable name when you do not plan to use that variable later on.

_是一个变量名,就像每个其他变量名一样(例如i)。 Ruby中的一个约定是,当您不打算稍后使用该变量时,使用_作为变量名。

#2


1  

In a function, the arguments are enclosed in parenthesis:

在函数中,参数括在括号中:

def my_function(arg1, arg2)
    ..
end

In a block, you use the pipes to enclose the arguments:

在块中,您使用管道来包含参数:

arr.each_with_index{ |item, index| .. }

In this case, the variable name choosen as the first argument for the block, was _.

在这种情况下,选择变量名作为块的第一个参数,是_。

#3


0  

You are calling the method each_with_index and passing it an anonymous function (or "block"). That block takes two parameters: the first represents an item in the array (or enumerable object) and the second represents its index (0 for the first element, 1 for the second, 2 for the third, and so on).

您正在调用方法each_with_index并将其传递给匿名函数(或“块”)。该块有两个参数:第一个表示数组中的项(或可枚举对象),第二个表示其索引(第一个元素为0,第二个元素为1,第三个元素为2,依此类推)。

Assigning the name _ in Ruby (and some other languages) is the conventional way of saying "I'm not going to use this." So each_with_index { |_, i| ... } means "In this block, i represents the index, and I don't care about the element itself so I'm not giving it a name."

在Ruby(以及其他一些语言)中分配名称_是传统的说法“我不打算使用它”。所以each_with_index {| _,i | ...}表示“在这个块中,我代表索引,我不关心元素本身所以我不给它起一个名字。”

#1


7  

_ is a variable name like every other variable name (for example i). It is a convention in Ruby to use _ as a variable name when you do not plan to use that variable later on.

_是一个变量名,就像每个其他变量名一样(例如i)。 Ruby中的一个约定是,当您不打算稍后使用该变量时,使用_作为变量名。

#2


1  

In a function, the arguments are enclosed in parenthesis:

在函数中,参数括在括号中:

def my_function(arg1, arg2)
    ..
end

In a block, you use the pipes to enclose the arguments:

在块中,您使用管道来包含参数:

arr.each_with_index{ |item, index| .. }

In this case, the variable name choosen as the first argument for the block, was _.

在这种情况下,选择变量名作为块的第一个参数,是_。

#3


0  

You are calling the method each_with_index and passing it an anonymous function (or "block"). That block takes two parameters: the first represents an item in the array (or enumerable object) and the second represents its index (0 for the first element, 1 for the second, 2 for the third, and so on).

您正在调用方法each_with_index并将其传递给匿名函数(或“块”)。该块有两个参数:第一个表示数组中的项(或可枚举对象),第二个表示其索引(第一个元素为0,第二个元素为1,第三个元素为2,依此类推)。

Assigning the name _ in Ruby (and some other languages) is the conventional way of saying "I'm not going to use this." So each_with_index { |_, i| ... } means "In this block, i represents the index, and I don't care about the element itself so I'm not giving it a name."

在Ruby(以及其他一些语言)中分配名称_是传统的说法“我不打算使用它”。所以each_with_index {| _,i | ...}表示“在这个块中,我代表索引,我不关心元素本身所以我不给它起一个名字。”