Sonntag, 16. Februar 2014

Next please! ... a Ruby iteration.

The Enumerators next helps to follow the guard pattern for enumerables. I already introduced the guard pattern itself in Return early! ... a Ruby guard pattern example. The following refactoring will map it to an iteration.
First the original code creating ".rb" script files starting with a Ruby shebang:
%w(people.csv task.rb job.rb).each do |file_name|
  if File.extname(file_name) == ".rb"
    File.open(file_name, "w") do |file|
      file << "#!/usr/bin/ruby"
    end
  end
end
which can be easily refactored to:
%w(people.csv task.rb job.rb).each do |file_name|
  next if File.extname(file_name) != ".rb"
  File.open(file_name, "w") do |file|
    file << "#!/usr/bin/ruby"
  end
end
Often the main purpose for next is readability, but it also can prevent you from maintaining awkward code. The idea behind is once again to stop processing the current iteration item as early as possible and process the next item.
Be explicit in your code intentions!

Supported by Ruby 2.1.0