Forum: Ruby delete from array while iterating

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Tarscher (Guest)
on 2009-03-25 18:51
(Received via mailing list)
Hi all,

I want to delete an element from an array when it matches a condition.
But I first want to print something to the screen when a amùcth is
found.

I know a.delete_if but can I somehow add that print to the screen next
to the condition? If not , is there an alternative way to delete from
an array while iterating?

thanks
Stijn
(Guest)
on 2009-03-25 19:04
(Received via mailing list)
[2,3,4,5,6].delete_if{|x| (x%2==0) && (puts x) }
2
4
6
Stefano C. (Guest)
on 2009-03-25 19:08
(Received via mailing list)
Alle Wednesday 25 March 2009, Tarscher ha scritto:
> thanks
> Stijn

In the block you can do anything you want. Just make sure you return a
true
value or a false value depending on whether the element should be
removed or
not. Here's an example:

a = [1,-1,-2,2,3]

a.delete_if do |i|
  if i < 0
    puts "#{i} will be deleted"
    true
  else false
  end
end

This will return [1,2,3] and give the following output:

-1 will be deleted
-2 will be deleted

I hope this helps

Stefano
lasitha (Guest)
on 2009-03-25 19:23
(Received via mailing list)
On Wed, Mar 25, 2009 at 10:30 PM, removed_email_address@domain.invalid
<removed_email_address@domain.invalid> wrote:
> [2,3,4,5,6].delete_if{|x| (x%2==0) && (puts x) }
> 2
> 4
> 6

Err, that won't work.  puts returns nil so the block will never return
true and none of the items will be removed.


We'd have to do:

arr.delete_if do |e|
  if e.matches(condition)
    puts e
    true
  end
end

Note: this can work w/o an else because the whole if expression will
return nil if none of the conditions match.

cheers,
lasitha
Robert K. (Guest)
on 2009-03-25 19:27
(Received via mailing list)
2009/3/25 Tarscher <removed_email_address@domain.invalid>:
> I want to delete an element from an array when it matches a condition.
> But I first want to print something to the screen when a amùcth is
> found.
>
> I know a.delete_if but can I somehow add that print to the screen next
> to the condition? If not , is there an alternative way to delete from
> an array while iterating?

What makes you think you cannot print in the block of a delete_if?

irb(main):009:0> a = (1..5).to_a
=> [1, 2, 3, 4, 5]
irb(main):010:0> a.delete_if {|x| printf "Found %4d\n", x; x % 3 == 0}
Found    1
Found    2
Found    3
Found    4
Found    5
=> [1, 2, 4, 5]
irb(main):011:0> a
=> [1, 2, 4, 5]

robert
This topic is locked and can not be replied to.