我正在尝试创建一系列我可以直接在Twitter上发送消息的人的哈希值。正确的数组看起来像[{id:12345,name:"john", profile_pic:"some_url"},{id:67890,name:"jim", profile_pic:"some_url"}]
我正在获取all_followers和all_friends并比较两者的内容。返回的每个对象都是一个哈希数组。我正在迭代一个数组并获取ID,然后遍历第二个数组并检查哈希是否包含该id值。如果是这样,我从原始哈希中获取一些细节并将其发送到最终发往我的浏览器的较小哈希。
执行此操作的代码是:
def get_direct_message_list(friend_list,follower_list)
names_and_pics = []
friend_list.each do |base|
follower_list.each do |compare|
if compare.has_value?(base["id"])
block_hash = {}
block_hash["id"] = base["id"]
block_hash["name"] = base["name"]
block_hash["profile_background_image_url"] = base["profile_background_image_url"]
names_and_pics << block_hash
end
end
end
names_and_pics
end
它基本上是有效的。我的测试套件如下所示,测试正在通过。
context "get_direct_message_list" do
it "should take friends and followers and return name, pic and twitter_id in one list" do
followers = [{"id"=>1, "name" => "john", "profile_background_image_url" => "http://somewhere.com"}, {"id"=>2},{"id"=>3, "name" => "mike", "profile_background_image_url" => "http://somewhere.com"}]
friends = [{"id"=>1, "name" => "john", "profile_background_image_url" => "http://somewhere.com"},{"id"=>5, "name"=>"someoneelse", "profile_background_image_url"=> "http://somewhere"},{"id"=>4},{"id"=>3, "name" => "mike", "profile_background_image_url" => "http://somewhere.com"}]
get_direct_message_list(friends, followers).should == [{"id"=>1, "name" => "john", "profile_background_image_url" => "http://somewhere.com"},{"id"=>3, "name" => "mike", "profile_background_image_url" => "http://somewhere.com"}]
end
end
我的问题是返回的数组有一些奇怪的重复,即特别是12和13的Twitter ID,biz stone和jack dorsey,两个人都没有关注我。它们各自在最终阵列中被复制3次和7次。我真的不确定该怎么看才能解决这个问题。我的第一个想法是当hashx.has_value?(13)
。has_value?的推特ID表示匹配是准确的时,134567' was being encountered but further experimentation with
之类的东西返回true。我能看到什么?
答案 0 :(得分:2)
如果compare.has_value?(base["id"])
中的任何等于true
,则行compare.values
将返回base["id"]
。
例如:
{:id => 12345, :foo => 2}.has_value?(2)
# => true
这可能会给你误报。很难说这是否是您问题的根本原因,但您可能希望比compare.has_value?(base["id"])
更明确。
如何更像compare["id"] == base["id"]
?