如何从阵列中删除哈希值?

时间:2018-02-09 09:30:04

标签: arrays ruby hash

我有一系列哈希

@employee_list = [{"id" => 375, "emp_name" => "emp1", "emp_no" => "e1"}, 
                  {"id" => 330, "emp_name" => "emp2", "emp_no" => "e2"}, 
                  {"id" => 38,  "emp_name" => "emp3", "emp_no" => "e3"},
                  {"id" => 49,  "emp_name" => "emp4", "emp_no" => "e4"}]

我想通过删除"id"值包含在其中的哈希值来过滤它:

@not_active_emp = ["49", "375"]

得到:

@employee_list = [{"id" => 330, "emp_name" => "emp2", "emp_no" => "e2"},
                  {"id" => 38,  "emp_name" => "emp3", "emp_no" => "e3"}]

1 个答案:

答案 0 :(得分:2)

您可以使用Array#reject。总体思路如下。

@not_active_emp = [49, 375]
@employee_list = [{"id" => 375, "emp_name" => "emp1", "emp_no" => "e1"}, 
                  {"id" => 330, "emp_name" => "emp2", "emp_no" => "e2"}, 
                  {"id" => 38,  "emp_name" => "emp3", "emp_no" => "e3"},
                  {"id" => 49,  "emp_name" => "emp4", "emp_no" => "e4"}]

@employee_list.reject { |hash| @not_active_emp.include? hash['id'] } 
  # => [{"id" => 330, "emp_name" => "emp2", "emp_no" => "e2"},
  #     {"id" => 38,  "emp_name" => "emp3", "emp_no" => "e3"}]