How can I implement this in Ruby? Is there any one line of code technique? Let's say I want to get rid of all the elements which are less than 3 of an integer array.
To remove array element on condition with JavaScript, we can use the array filter method. let ar = [1, 2, 3, 4]; ar = ar.
Remove an Array Element Using the delete_if Method There is also a delete_if method that deletes an element that matches a condition from an array. This also mutates the original array. Note that reject! also modifies arrays in place and can be used similarly as delete_if .
The shift() is an inbuilt function in Ruby returns the element in the front of the SizedQueue and removes it from the SizedQueue. Parameters: The function does not takes any element.
You can use either new_array = array.reject {|x| x < 3}
(reject
returns a new array) or array.reject! {|x| x < 3}
(reject!
aka delete_if
modifies the array in place).
There's also the (somewhat more common) select
method, which acts like reject
except that you specify the condition to keep elements, not to reject them (i.e. to get rid of the elements less than 3, you'd use new_array = array.select {|x| x >= 3}
).
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