哈希 select() 和 select!() 方法在 Ruby 中
在 Ruby 中,当我们想要基于条件找到哈希中的数组时,我们要使用 select() 方法,并且当我们想要检查哈希中的数组是否存在时,我们要使用 select!() 方法。
我们来探索一下 哈希 select() 方法的一些示例,以更好地理解它。
示例 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"}}
"
输出
A select present in Hash!: {"first"=>150}
示例 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"}}
"
输出
second select form : {"first"=>150} third select form : {"first"=>150}
现在我们来看看 Ruby 中 哈希 select!() 方法的一些示例。
示例 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"}}
"
输出
A select present in Hash!: {"first"=>150}
示例 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"}}
"
输出
second select form : third select form : {"first"=>150}
广告