[Ruby] Extract only the elements that match the conditions and create a new array. filter and select

This is a personal memo.

There are select and filter as methods to extract only the elements that match the conditions and create a new array.

This is the same for both. Looking at the official page of ruby, select is used in the example of the filter method.

image.png

Ruby Official Array # filter


## range object For range objects from 1 to 3, only the numerical values ​​corresponding to 2 or less are extracted and an array is created.

select


range = 1..3   #[1,2,3]
range2 = range.select{|x| x<=2}

p range2
#output
[1, 2]

filter


range = 1..3   #[1,2,3]
range2 = range.filter{|x| x<=2}

p range2
#output
[1, 2]

The result is the same for both filter and select.


## Array

select


arr = [1,2,3]
arr2 = arr.select{|x| x<=2}

p arr2
#output
[1, 2]

## object For objects, set two variables. The first variable is the key and the second variable is the value.

python


obj = {:a=>1, :b=>2, :c=>3}
obj2 = obj.select{|x, y| y<=2}

p obj2
#output
{:a=>1, :b=>2}

Unlike the map method, the processing result is returned as an object. (In the case of map, an array is returned)

Recommended Posts

[Ruby] Extract only the elements that match the conditions and create a new array. filter and select
[Ruby] How to extract a specific value from an array under multiple conditions [select / each]
[ruby] Creating a program that responds only to specific conditions
Install Rails in the development environment and create a new application
[Ruby] I want to extract only the value of the hash and only the key
[Ruby] A program that uses search and each_with_index
A description that only the poster can access
[Ruby on Rails] Implementation of validation that works only when the conditions are met
A program that outputs a number greater than or equal to the input integer and a number less than the input integer from an array with 50 elements.