What does this mean in Ruby?

In this code:

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

What does underline pipe mean?

+8
ruby
source share
3 answers

_ is the name of the variable, just like any other variable name (e.g. i ).

In Ruby, it is customary to use _ as the variable name or the prefix variable name with _ (for example, _i ) as an indication that you do not plan to use this variable in the future.

In your example, each_with_index two values ​​at each iteration step: the current element and the current index.

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

The author of the code should have named both values, but decided to use the variable name _ to indicate that they do not care about the current value, only about the current index.

+9
source share

In a function, arguments are enclosed in parentheses:

 def my_function(arg1, arg2) .. end 

In the block, you use pipes to add arguments:

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

In this case, the variable name selected as the first argument to the block was _ .

+2
source share

You call the each_with_index method and pass it an anonymous function (or "block"). This block takes two parameters: the first represents an element in the array (or an enumerated object), and the second represents its index (0 for the first element, 1 for the second, 2 for the third, etc.).

Assigning the name _ in Ruby (and some other languages) is the usual way of saying "I will not use this." So each_with_index { |_, i| ... } each_with_index { |_, i| ... } means "In this block, i represents the index, and I do not care about the element itself, so I do not give it a name."

+1
source share

All Articles