.select Method

Writing loops can become cumbersome as the situation becomes more difficult. Certain methods are out there to help you simplify your code and still return the same results. Select is a method that helps you out with this.

Here is an example of how you’d write an each loop to return the even numbers within a given array:

numbers = [1, 2, 4, 2]
even_numbers = []
numbers.each do |number|
if number.even?
even_numbers << number
end
end
p even_numbers
=>  [2, 4, 2]

Here is how you can simplify the code using the select method:

numbers = [1, 2, 4, 2]
even_numbers = numbers.select {|number| number.even? }
p even_numbers
=> [2, 4, 2]

Here’s another way to use the .select method with an array of hashes to return certain data:

movies = [
{id: 1, title: "Die Hard", rating: 4.0},
{id: 2, title: "Bad Boys", rating: 5.0},
{id: 3, title: "The Chamber", rating: 3.0},
{id: 4, title: "Fracture", rating: 2.0}
]
new_hash = movies.select{|movie| movie[:rating] < 4.0}
p new_hash
=>  [{:id=>3, :title=>"The Chamber", :rating=>3.0}, {:id=>4, :title=>"Fracture", :rating=>2.0}]

The .select method works through each “movie” checking to see if the movie[:rating] is less than 4.0. If the movie is less than 4.0, the method adds that movie hash to the “new_hash”.

Like what you read? Give Kyle Gundry a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.