Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop hash structure: Ruby on rails

I want to delete data from a hash table using a specific range of values.

Example:

hash = { t:1, y:9, k:10, a:30, b:40, c:50, d:80, e:60, z:100, l:3, n:9, f:20 }

Given an array of numbers: array = [10, 30, 40, 50, 80, 60, 100] (is exactly the range of the center of the table)

I want the result to be:

hash: {k:10, a:30, b:40, c:50, d:80, e:60, z:100}

Notes that never eliminated data that is in the middle of the structure.

like image 883
dijane Avatar asked Feb 13 '23 11:02

dijane


2 Answers

Look at the select method.

[6] pry(main)> hash.select { |k,v| array.include?(v) }
=> {:k=>10, :a=>30, :b=>40, :c=>50, :d=>80, :e=>60, :z=>100}
like image 156
Nick Veys Avatar answered Feb 15 '23 09:02

Nick Veys


results = {}
hash.each { |k, v| results[k] = v if array.include?(v) }
puts results

output:

{:k=>10, :a=>30, :b=>40, :c=>50, :d=>80, :e=>60, :z=>100}
like image 37
Anthony Avatar answered Feb 15 '23 11:02

Anthony