Keeping it Small and Simple

2008.02.12

Use Ruby’s Array#delete_if

Filed under: Ruby Programming — Tags: , — Lorenzo E. Danielsson @ 15:20

In case you didn’t know, Ruby has a convenient way of allowing you to remove items from an array called delete_if. You simply pass in a block with an expression. All items in the array for which the block expression evaluates to true are removed. Here are a few simple examples:

Remove a specific item:

 1 #! /usr/bin/ruby
 2
 3 wd = %w[Monday Tuesday Wednesday Thursday Friday Saturday Sunday]
 4
 5 # Tell me why
 6 # I don’t like Mondays
 7 # I want to shoot
 8 # The whole day down
 9 wd.delete_if { |day| day == "Monday" }
10 p wd

Remove all words that end with the letter s:

1 #! /usr/bin/ruby
2
3 words = %w[eggs ham vinegar salt pancakes wine oranges]
4 words.delete_if { |w| w =~ /s$/ }
5 p words

Remove odd numbers.

1 #! /usr/bin/ruby
2
3 nums = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
4 nums.delete_if { |n| n % 2 > 0 }
5 p nums

Remove people under 18.

 1 #! /usr/bin/ruby
 2
 3 class Person
 4   attr_reader :name, :age
 5
 6   def initialize(name, age)
 7     @name = name
 8     @age = age
 9   end
10
11   def to_s
12     @name
13   end
14 end
15
16 class Bar
17   def enter(group)
18     group.delete_if { |person| person.age < 18 }
19     puts "#{group.join(, )} are welcome!"
20   end
21 end
22
23 drunken_sailor = Bar.new
24 drunks = [
25   Person.new("Tom", 28),
26   Person.new("Dick", 17),
27   Person.new("Harry", 18)
28 ]
29
30 drunken_sailor.enter drunks

Delete all items:

1 #! /usr/bin/ruby
2
3 nums = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
4 nums.delete_if { true }
5 p nums

Delete no items (a way of doing a NOP in Ruby).

1 #! /usr/bin/ruby
2
3 nums = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
4 nums.delete_if { false }
5 p nums

There you have it. Using delete_if makes your life simpler, so just use it.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: