2
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

5 Answers 5

2
input_hash.map(&:values).to_h.values_at(*check).join(", ")
# => "george, nancy"
Sign up to request clarification or add additional context in comments.

Comments

1
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"

Comments

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

Comments

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

Comments

0

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"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.