Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash/Array delete_if without a block

Tags:

ruby

According to Ruby Hash/Array documentation, the delete_if method returns an enumerator if no block is given. How is this useful? Can someone give an example to demonstrate this pattern?

like image 816
Xiaotian Guo Avatar asked Mar 19 '26 05:03

Xiaotian Guo


2 Answers

There are some methods defined on Enumerator that give flexibility to iterators. One such method I often use is with_index.

p %w[a b c d e f].delete_if.with_index{|_, i| i.even?}
# => ["b", "d", "f"]

If this was to be done without Enumerator class, all kinds of methods have to be defined, including delete_if_with_index, and that is not a good thing.

like image 123
sawa Avatar answered Mar 21 '26 20:03

sawa


The enumerator will just allow you to run the block later. For example, if you had a method that specifically handled the delete if for several different objects, you could pass it the enumerator.

In the example below, it will print 1, 3, 5

arr = [0,1,2,3,4,5]
enumerator = arr.delete_if
enumerator.each { |el| el.even? }
puts arr.join(', ')
like image 41
Cory Gagliardi Avatar answered Mar 21 '26 22:03

Cory Gagliardi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!