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?
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.
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];
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With