input_hash = [{"id"=>"123", "name"=>"ashly"}, {"id"=>"73", "name"=>"george"}, {"id"=>"175", "name"=>"nancy"}, {"id"=>"433", "name"=>"grace"}]
check = ["73", "175"]
output => "george, nancy"
我可以猜到可以使用"选择"。但不太确定它如何在数组中选择两个值
input_hash.map(&:values).to_h.values_at(*check).join(", ")
# => "george, nancy"
check.flat_map{|c| input_hash.select{|aa| aa["id"] == c}}.map{|a| a["name"]}.join(", ")
=> "george, nancy"
或
input_hash.select{|h| h["name"] if check.include? h["id"]}.map{|aa| aa["name"]}.join(", ")
=> "george, nancy"
input_hash.map { |hash| hash["name"] if check.include?(hash["id"]) }.compact
input_hash.select {|h| check.include?(h["id"])}.map {|h| h["name"]}.join(", ")
试试这个:
def get_output_hash(input_hash, ids)
input_hash.each do |hash|
if ids.include?(hash["id"])
p hash["name"]
end
end
end
这样称呼它:-
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"])