I have an array of elements in Ruby
[2,4,6,3,8]
I need to remove elements with value 3
for example
How do I do that?<
If you also want to make this deletion operation chainable, so you can delete some item and keep on chaining operations on the resulting array, use tap
:
[2, 4, 6, 3, 8].tap { |ary| ary.delete(3) }.count #=> 4
I think I've figured it out:
a = [3, 2, 4, 6, 3, 8]
a.delete(3)
#=> 3
a
#=> [2, 4, 6, 8]
I like the -=[4]
way mentioned in other answers to delete the elements whose value are 4.
But there is this way:
irb(main):419:0> [2,4,6,3,8,6].delete_if{|i|i==6}
=> [2, 4, 3, 8]
irb(main):420:0>
mentioned somewhere in "Basic Array Operations", after it mentions the map
function.