1

I would like to create a new array B_array based on an existing array A A_array. If that item in A_array has a certain field then add it into B_array.

Currently this is what I have and its putting everything into B_array:

B_array = A_array.map {|item| if item.name == 'Josh'}

A_array:

[id:0,name:"Josh",email:"josh@josh@gmail.com"],
[id:1,name:"Scott",email:"scott@josh@gmail.com"],
[id:2,name:"Josh",email:"dan@josh@gmail.com"]

Desired output for B_array:

[id:0,name:"Josh",email:"josh@josh@gmail.com"],
[id:2,name:"Josh",email:"dan@josh@gmail.com"]

Thanks!

4

1 回答 1

6

使用.select

a = [{id:0,name:"Josh",email:"josh@josh@gmail.com"},
     id:1,name:"Scott",email:"scott@josh@gmail.com"}]
b = a.select { |i| i[:name] == 'Josh' }

.select将根据您给它的条件进行过滤并返回通过测试的元素数组。

于 2012-07-12T00:03:05.963 回答