过滤一组哈希Ruby

时间:2015-07-17 07:42:45

标签: ruby-on-rails ruby

我有一系列哈希:

[
   [0] {
    "10:45" => 40,
    "11:00" => 40,
    "11:15" => 40,
    "11:30" => 40
    "13:30" = >35,
    "14:00" => 40,
    "15:00" => 40
     },
   [1] {
    "12:00" => 38,
    "12:45" => 39,
    "13:00" => 39,
    "13:15" => 39,
    "13:30" => 39
    }
]

我需要获得这个新的过滤数组:

 [
   [0] {
    "10:45" => 40,
    "13:30" = >35,
    "14:00" => 40
     },
   [1] {
    "12:00" => 38,
    "12:45" => 39
    }
]

换句话说"如果值在值#34之前等于右边,则删除键/值。

1 个答案:

答案 0 :(得分:1)

让我们尝试一下,你有这个数组

array = [
   {
    "10:45" => 40,
    "11:00" => 40,
    "11:15" => 40,
    "11:30" => 40,
    "13:30" = >35,
    "14:00" => 40,
    "15:00" => 40
   },
   {
    "12:00" => 38,
    "12:45" => 39,
    "13:00" => 39,
    "13:15" => 39,
    "13:30" => 39
   }
]

让我们删除重复的值

def get_results(array)
  final_array = []

  array.each do |hash|
    final_hash = {}

    hash.each do |key, value|
      final_hash[key] = value unless final_hash.values.last == value
    end
    final_array << final_hash
  end
  final_array
end

希望这有帮助!