Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Array#delete while iterating over the array?

I have an array that I want to iterate over and delete some of the elements. This doesn't work:

a = [1, 2, 3, 4, 5] a.each do |x|   next if x < 3   a.delete x   # do something with x end a #=> [1, 2, 4] 

I want a to be [1, 2]. How can I get around this?

like image 759
Adrian Avatar asked Jul 15 '10 22:07

Adrian


People also ask

How do you use an array?

Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

What is the use of array explain with example?

An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it. int data[100];

Why is it important to use array?

1) Array stores data elements of the same data type. 2) Maintains multiple variable names using a single name. Arrays help to maintain large data under a single variable name. This avoid the confusion of using multiple variables.


1 Answers

a.delete_if { |x| x >= 3 }

See method documentation here

Update:

You can handle x in the block:

a.delete_if do |element|   if element >= 3     do_something_with(element)     true # Make sure the if statement returns true, so it gets marked for deletion   end end 
like image 159
Chubas Avatar answered Sep 23 '22 22:09

Chubas