- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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}
Advertisements