deleting an object in array, based on object.attribute

Discussion in 'Ruby' started by Josselin, Aug 17, 2007.

  1. Josselin

    Josselin Guest

    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
    Josselin, Aug 17, 2007
    #1
    1. Advertising

  2. 2007/8/17, 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 ?


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

    robert
    Robert Klemme, Aug 17, 2007
    #2
    1. Advertising

  3. Josselin

    Josselin Guest

    On 2007-08-17 10:42:16 +0200, "Robert Klemme"
    <> said:

    > 2007/8/17, 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 ?

    >
    > 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 !
    Josselin, Aug 17, 2007
    #3
  4. Josselin

    Peña, Botp Guest

    From: Josselin [mailto:]=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
    Peña, Botp, Aug 17, 2007
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    2
    Views:
    1,067
    Henry S. Thompson
    Mar 6, 2006
  2. Harry Barker
    Replies:
    2
    Views:
    507
    Alf P. Steinbach
    Apr 19, 2006
  3. senthil
    Replies:
    10
    Views:
    389
  4. crea
    Replies:
    2
    Views:
    399
    Nobody
    Dec 28, 2012
  5. Marc Aymerich
    Replies:
    0
    Views:
    67
    Marc Aymerich
    Nov 24, 2013
Loading...

Share This Page