Array select

i have 2 arrays of objects: dates and places

dates have attribute place_id
and places have id

I must to selezionate all places that have id in array of objects dates.

dates.select{|obj| obj.place_id in places[].id }

How i can replace "in places[].id " to works it?
Thanks

2007/11/12, Luca R. [email protected]:

i have 2 arrays of objects: dates and places

dates have attribute place_id
and places have id

I must to selezionate all places that have id in array of objects dates.

dates.select{|obj| obj.place_id in places[].id }

How i can replace "in places[].id " to works it?

Create a Set of place ids and test against that when selecting.
Alternative use #any? on places to test for a place with the current
date’s place_id but this is very inefficient.

Cheers

robert

Luca R. wrote:

i have 2 arrays of objects: dates and places

dates have attribute place_id
and places have id

I must to selezionate all places that have id in array of objects dates.

dates.select{|obj| obj.place_id in places[].id }

How i can replace "in places[].id " to works it?
Thanks

You could use Array#collect, which creates a new array out of another
array, taking a block of code that processes an element of the old array
and spits out something to go into the new array.

so,
places[].id

would be
places.collect{ |place| place.id}

You can then ask if obj.place_id is in this, as follows:

dates.select{ |obj| places.collect{ |place|
place.id}.include?(obj.place_id) }

I think that’s what you’re after (i’m not exactly sure from your
question, sorry).

Max W. wrote:

Luca R. wrote:

i have 2 arrays of objects: dates and places

dates have attribute place_id
and places have id

I must to selezionate all places that have id in array of objects dates.

dates.select{|obj| obj.place_id in places[].id }

How i can replace "in places[].id " to works it?
Thanks

You could use Array#collect, which creates a new array out of another
array, taking a block of code that processes an element of the old array
and spits out something to go into the new array.

so,
places[].id

would be
places.collect{ |place| place.id}

You can then ask if obj.place_id is in this, as follows:

dates.select{ |obj| places.collect{ |place|
place.id}.include?(obj.place_id) }

I think that’s what you’re after (i’m not exactly sure from your
question, sorry).

Just occurred to me that this is horribly inefficient as you remake the
collection for each member of dates! It would be better to make the new
array first:

place_ids = places.collect{ |place| place.id}
dates.select{ |obj| place_ids.include?(obj.place_id) }