user3636388
user3636388

Reputation: 237

How to extract hashes from an array of hashes based on array value

input_hash = [{"id"=>"123", "name"=>"ashly"}, {"id"=>"73", "name"=>"george"}, {"id"=>"175", "name"=>"nancy"}, {"id"=>"433", "name"=>"grace"}]

check = ["73", "175"]


output => "george, nancy"

I can guess 'select' can be used. But not very sure how it can select both values in the array

Upvotes: 2

Views: 2108

Answers (5)

sawa
sawa

Reputation: 168101

input_hash.map(&:values).to_h.values_at(*check).join(", ")
# => "george, nancy"

Upvotes: 2

Ilya
Ilya

Reputation: 13487

input_hash.select {|h| check.include?(h["id"])}.map {|h| h["name"]}.join(", ")

Upvotes: 1

Abhi
Abhi

Reputation: 4261

Try this:

def get_output_hash(input_hash, ids)
  input_hash.each do |hash|
    if ids.include?(hash["id"])
      p hash["name"]
    end
  end
end

Call it like:-

input_hash = [{"id"=>"123", "name"=>"ashly"}, {"id"=>"73", "name"=>"george"}, {"id"=>"175", "name"=>"nancy"}, {"id"=>"433", "name"=>"grace"}]

get_output_hash(input_hash, ["73", "175"])

Upvotes: 0

Rajarshi Das
Rajarshi Das

Reputation: 12320

check.flat_map{|c| input_hash.select{|aa| aa["id"] == c}}.map{|a| a["name"]}.join(", ")
=> "george, nancy"

or

input_hash.select{|h| h["name"] if check.include? h["id"]}.map{|aa| aa["name"]}.join(", ")
=> "george, nancy"

Upvotes: 1

Esse
Esse

Reputation: 3298

input_hash.map { |hash| hash["name"] if check.include?(hash["id"]) }.compact

Upvotes: 1

Related Questions