仰望键数组散列的红宝石阵列如Excel VLOOKUP上 [英] Looking up an array of keys on an array of hashes in ruby like excel vlookup

查看:111
本文介绍了仰望键数组散列的红宝石阵列如Excel VLOOKUP上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这帖子是非常相似,我的previous之一,但数据结构是不同的位置:
<一href=\"http://stackoverflow.com/questions/9981671/joining-an-array-of-keys-to-a-hash-with-key-value-pairs-like-excel-vlookup\">Joining键数组的哈希与Excel等VLOOKUP

键值对

从我Mysql2 ::结果我的数据回来这样的阵列哈希:

 数据= [{ISBN=&GT; 1234,标题=&gt;中的苹果},{ISBN=&GT; 5678,标题=&gt;中的香蕉},{ISBN=&GT; 2121,标题=&gt;中车}]

和我原来的,我想比较的ISBN的列表是该数组:

 的ISBN =1234,2121,5454,5678]

我正在寻找它使用的ISBN数组,并返回这样的结果的函数:

 结果= [{ISBN=&gt;中1234,标题=&gt;中的苹果},{ISBN=&GT; 2121,标题=&gt;中车},零,{ISBN=&gt;中5678,标题=&gt;中芭}]

在驾驶阵列的ISBN ...想象一下这样做的ISBN号到数据VLOOKUP ......不在数据中的任何项目,但在ISBN编号应返回零。 ISBN号的原始顺序应返回,返回数据应该是哈希值的数组。


解决方案

  isbns.map {|书号| data.find {| H | H [ISBN] == ISBN}}
#=&GT; [{ISBN=&gt;中1234,标题=&gt;中的苹果},{ISBN=&gt;中2121,标题=&gt;中车},零,{ISBN =&gt;中5678,标题=&gt;中芭}]

This post is very similar to my previous one, but the data structures are different here: Joining an array of keys to a hash with key value pairs like excel vlookup

My data from my Mysql2::Result comes back like this array of hashes:

data = [{"isbn" => "1234", "title"=>"apple"},{"isbn" => "5678", "title"=>"banana"},{"isbn" => "2121", "title"=>"car"}]

And my original list of isbns that I would like to compare is this array:

isbns = ["1234","2121", "5454", "5678"]

I'm seeking a function which uses the isbns array and returns a result like this:

result = [{"isbn"=>"1234","title"=>"apple"}, {"isbn"=> "2121", "title"=>"car"}, nil, {"isbn"=>"5678","title"=>"banana"}]

The "driving" array is the isbns... imagine doing a vlookup from isbns to data ... any items that are not in data, but in isbns should return nil. The original order of isbns should be returned, and the return data should be an array of hashes.

解决方案

isbns.map { |isbn| data.find { |h| h["isbn"] == isbn} }
#=> [{"isbn"=>"1234", "title"=>"apple"}, {"isbn"=>"2121", "title"=>"car"}, nil, {"isbn"=>"5678", "title"=>"banana"}]

这篇关于仰望键数组散列的红宝石阵列如Excel VLOOKUP上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆