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
input_hash.map(&:values).to_h.values_at(*check).join(", ")
# => "george, nancy"
input_hash.select {|h| check.include?(h["id"])}.map {|h| h["name"]}.join(", ")
input_hash.map { |hash| hash["name"] if check.include?(hash["id"]) }.compact
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"
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"])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.