[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

deleting an object in array, based on object.attribute

Josselin

8/17/2007 8:36:00 AM

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

3 Answers

Robert Klemme

8/17/2007 8:42:00 AM

0

2007/8/17, Josselin <josselin@wanadoo.fr>:
> 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

Josselin

8/17/2007 8:46:00 AM

0

On 2007-08-17 10:42:16 +0200, "Robert Klemme"
<shortcutter@googlemail.com> said:

> 2007/8/17, Josselin <josselin@wanadoo.fr>:
>> 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 !

Peña, Botp

8/17/2007 8:50:00 AM

0

From: Josselin [mailto:josselin@wanadoo.fr]
# 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

delete_if changes the array

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

reject creates another array copy

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

select is like reject but w reverse logic

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


kind regards -botp