deleting an object in array, based on object.attribute

J

Josselin

I have an array anArray = [ object_1, object_2, ...... object_n]

I would like to delete an object in it, if object.attribute_x = anInteger

what is the dryest way to do it vs a C-style loop on each item of the array ?

thanks fyh

joss
 
R

Robert Klemme

2007/8/17 said:
I have an array anArray = [ object_1, object_2, ...... object_n]

I would like to delete an object in it, if object.attribute_x = anInteger

what is the dryest way to do it vs a C-style loop on each item of the array ?

irb(main):001:0> %w{foo bar peter mountain}.delete_if {|s| s.length > 3}
=> ["foo", "bar"]

robert
 
J

Josselin

2007/8/17 said:
I have an array anArray = [ object_1, object_2, ...... object_n]

I would like to delete an object in it, if object.attribute_x = anInteger

what is the dryest way to do it vs a C-style loop on each item of the array ?

irb(main):001:0> %w{foo bar peter mountain}.delete_if {|s| s.length > 3}
=> ["foo", "bar"]

robert

thanks Robert.. missed the delete_if { block } in reading my doc !
 
P

Peña, Botp

From: Josselin [mailto:[email protected]]=20
# I have an array anArray =3D [ object_1, object_2, ...... object_n]
# I would like to delete an object in it, if=20
# object.attribute_x =3D anInteger

delete_if changes the array

irb(main):055:0> a=3D["a",1,"b",2,3,"c",4]
=3D> ["a", 1, "b", 2, 3, "c", 4]
irb(main):056:0> a.delete_if{|x| x.is_a? Integer}
=3D> ["a", "b", "c"]
irb(main):057:0> a
=3D> ["a", "b", "c"]

reject creates another array copy

irb(main):061:0> a.reject{|x| x.is_a? Integer}
=3D> ["a", "b", "c"]

select is like reject but w reverse logic

irb(main):066:0> a.select{|x| not x.is_a? Integer}
=3D> ["a", "b", "c"]


kind regards -botp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top