Hash select() and select!() methods in Ruby



In Ruby, we make use of the select() method when we want to find the array from the hash based on the condition and we make use of the select!() method when we want to check whether the array from the hash is present or not.

Let's explore a few examples of the hash select() method to understand it better.

Example 1

# Hash.select() method # Hash value first = { "first" => 150, "second" => 200 } # Hash value second = {"first" => 150} # Hash value third = {"first" => 150, "third" => 300, "second" => 200} # select! Value puts "A select present in Hash!: #{first.select {|key,value| key < "second"}}

"

Output

A select present in Hash!: {"first"=>150} 

Example 2

# Hash.select() method # declaring Hash value second = {"first" => 150} # declaring Hash value third = {"first" => 150, "third" => 300, "second" => 200} # select Value puts "second select form : #{second.select{|key, value|value < 200}}

" puts "third select form : #{third.select{|key, value|key < "second"}}

"

Output

second select form : {"first"=>150} third select form : {"first"=>150}

Now let's see some examples of the hash select!() method in Ruby.

Example 3

# Hash.select!() method # Hash value first = { "first" => 150, "second" => 200 } # Hash value second = {"first" => 150} # Hash value third = {"first" => 150, "third" => 300, "second" => 200} # select! Value puts "A select present in Hash!: #{first.select! {|key, value| key < "second"}}

"

Output

A select present in Hash!: {"first"=>150}

Example 4

# Hash.select!() method # declaring Hash value second = {"first" => 150} # declaring Hash value third = {"first" => 150, "third" => 300, "second" => 200} # select Value puts "second select form : #{second.select!{|key, value| value < 200}}

" puts "third select form : #{third.select!{|key, value| key < "second"}}

"

Output

second select form : third select form : {"first"=>150}
Updated on: 2022-01-25T10:46:50+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements