Rubyize This: Live in Vancouver. Refactoring #3

written by Scott on January 26th, 2008 @ 09:02 PM

Here’s the final refactoring from the Rubyize This workshop. See the first refactoring for an explanation of what’s going on and why this code is so darn ugly! The second refactoring is worth checking out as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env ruby

def delete_large_files(directory, max_size)
  
  # Make sure directory ends in a slash
  if directory !~ /\/$/
    directory += '/'
  end
  
  # Find all of the files in the directory 
  files = Dir.glob(directory + '*')
  
  # Delete all files with size larger than max_size
  for file in files
    size = File.size(file)
    if size >= max_size
      File.delete(file)
    end
  end
  
end

max_size = 1024 * 50 # 50 kb
directory = './files_to_delete'
delete_large_files(directory, max_size)

This was the final refactoring, and the end of the conference, so we sort of ran out of time.

I didn’t get a change to show off my solution. Here it is.

1
2
3
4
5
6
7
8
9
def delete_large_files(dir, max_size)

  files_to_delete = Dir.glob(File.join(dir, '*')).select do |file|
    File.size(file) > max_size
  end

  File.delete(*files_to_delete)

end

What’s going on with that File.delete call?

First, File.delete takes multiple arguments and deletes all of them.

Second, I used the asterisk operator. From here:

“The asterisk operator may also precede an Array argument in a method call. In this case the Array will be expanded and the values passed in as if they were separated by commas.”

I don’t think I’ve every actually used the asterisk operator in production code, but it sure came in handy here.

Comments

  • Sam Livingston-Gray on 26 Jan 21:41

    I use the splat operator regularly (perhaps not daily, but certainly once every week or two). Among other things, it's a handy way to peel off the first N elements of an arglist and pass the rest along to some other function -- sort of a reverse currying, if you will. (=
    
    def do_something_complicated(*gaggle_of_args)
      foo, bar, *others = *gaggle_of_args
      do_step_one(foo, bar)
      do_step_two(*gaggle_of_args)
    end
    
    Hmm... that example looks a bit crap, actually. But the splat is still my friend. And it's clearly time for me to go to sleep. (=

Comments are closed