2016-04-21 86 views
0

的阵列我有一个阵列像哈希:红宝石,我如何比较两对项目的散列

arry = {hash1, hash2, hash3,hash4 ....hash_N} 

每个哈希,

hash1 ={ "deviceId"=>"868403021230682", "osVersion"=>"6.0", "deviceOS"=>"Android", 
"appVersion"=>"1.7.2", "action"=>"Enter"} 
hash2 = { "deviceId"=>"868403021230682", "osVersion"=>"6.0", "deviceOS"=>"Android", 
"appVersion"=>"1.7.2", "action"=>"Leave"} 

,因为它有可能为每个hash "action"=>"Enter" or "Leave"不会总是显示为一对,例如,动作对于hash3,hash4,hash5可能都是“Enter”。我的想法是只考虑两个哈希谁可以做一个像hash1和hash2,从数组中删除其他数组或将其放入其他数组。 所以新阵列应该只包含[hash1, hash2, hash7,hash8],可以说hash7和8也是一对。

我应该使用each_with_index吗?我的代码是这样的:

def get_result(doc) 
result = [] 

doc.each_slice(2).map { |pair| 
    pair.each_with_index { |element, index| 
    if (pair[index].has_value?([:action] => "enter") &&pair[index+1].has_value?([:action] => "Leave") 
     result.push(pair) 
    end 
    } 
} 
end 

if语句不工作的权利,那种困惑如何使用each_with_index希望有人能帮助我

回答

1

根据您的方法创建的,你的方式可以这样来做:

def get_result(doc) 
    doc.each_sli­ce(2).to_a­.map{ |ah| ah if ah[0][:action] == 'Enter'­ && ah[1]­[:action] == 'Leave'­}.compact.flatten 
end 

说明

在v易变的doc是一个散列数组[hash1, hash2, ...]当我们创建doc.each_slice(2).to_a时会返回一对散列数[[hash1, hash2],[hash3,hash4]...],现在当我们做map并得到每个订单('Enter','Leave')有actions的散列对时,我们得到一个具有这样的零值的数组,如[[hash1,hash2],nil,[hash5,hash6]..]。我们使用compact来删除nil的值。现在阵列是这样[[hash1,hash2],[hash5,hash6]..](对哈希数组)和预期结果是哈希的数组,这就是为什么我们需要flatten,它会删除内部数组并返回这样[hash1, hash2, hash5, hash6 ...]

数组如果您需要要获得已删除的哈希列表,我认为如果添加其他方法来执行它会更好。否则,您可以使get_result方法返回两个数组。

这里是你如何能做到这:

def get_result(doc) 
    removed_elms = [] 
    result = doc.each_sli­ce(2).to_a­.map do |ah| 
    # if you just need them different (not the first one 'Enter' and the second one 'Leave') you need to set the commented condition 
    # if ['Enter','Leave'].include?(ah[0][:action] && ah[1][:action]) && ah[0][:action] != ah[1][:action] 
    if ah[0][:action] == 'Enter'­ && ah[1]­[:action] == 'Leave' 
    ah 
    else 
    removed_elms << ah 
    nil 
    end 
    end.compact 
    [result.flatten, removed_elms.flatten] 
end 
+0

我怎么能抛弃哈希值保存到另一个阵列?为什么需要平坦?我只想消除未配对的哈希。如果可能的话,你会介意一下吗?谢谢 – roccia

+0

@roccia我更新了我的答案,希望对你有帮助 –

+0

谢谢!这很清楚! – roccia