Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this |_ mean in Ruby?

Tags:

ruby

In this code:

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

what does pipe underscore mean?

like image 387
Christopher Kummelstedt Avatar asked Mar 26 '16 22:03

Christopher Kummelstedt


People also ask

What are Ruby symbols&how do they work?

- RubyGuides What Are Ruby Symbols & How Do They Work? A symbol looks like this: Some people confuse symbols with variables, but they have nothing to do with variables… … a symbol is a lot more like a string. So what are the differences between Ruby symbols & strings? Strings are used to work with data. Symbols are identifiers.

What is a ruby identifier?

Ruby identifiers are consist of alphabets, decimal digits, and the underscore character, and begin with a alphabets(including underscore). There are no restrictions on the lengths of Ruby identifiers.

What is the difference between operators in Ruby?

Most of operators are just method invocation in special form. But some operators are not methods, but built in to the syntax: In addition, assignment operators ( += etc.) are not user-definable. Control structures in Ruby are expressions, and have some value. Ruby has the loop abstraction feature called iterators.

What is defined character set in Ruby?

defined? The character set used in the Ruby source files for the current implementation is based on ASCII. The case of characters in source files is significant. All syntactic constructs except identifiers and certain literals may be separated by an arbitrary number of whitespace characters and comments.


1 Answers

_ is a variable name like every other variable name (for example i).

It is a convention in Ruby to use _ as a variable name or prefix variable names with _ (like _i) as an indication that you do not plan to use that variable later on.

In your example, each_with_index yields two values in each step of the iteration: The current element and the current index.

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

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

like image 156
spickermann Avatar answered Sep 27 '22 21:09

spickermann