Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to DRY in Ruby?

Tags:

ruby

dry

How could I make this shorter and extendable:

  def overview
    puts "All As:"
    for f in @a
      puts f
    end
    puts "\n"  

    puts "All Bs:"
    for f in @b
      puts f
    end
  end
like image 995
poseid Avatar asked Oct 01 '10 11:10

poseid


2 Answers

for f in @a
  puts f
end

can we written

puts @a.join("\n")

In the general case, when you want to do something with several arrays you can put the arrays into an array and then use each e.g.

[@a, @b].each do |list|
  list.each { |value| puts value }
end

and once you get onto doing something more complicated than just printing out the values it makes sense to use the extract method refactoring on the operation you're performing e.g.

[@a, @b].each do |list|
  do_something_with list
end

Finally, if you need to keep descriptive labels ("All As" etc.) you can use a hash:

{'As' => @a, 'Bs' => @b}.each_pair do |label, values|
    puts "All #{label}"
    puts values.join("\n")
end
like image 74
mikej Avatar answered Oct 11 '22 14:10

mikej


def print_all(header, ary)
  puts header
  for f in ary
    puts f
  end
end

def overview
  print_all("All As:", @a)
  puts
  print_all("All Bs:", @b)
end
like image 33
Hongli Avatar answered Oct 11 '22 13:10

Hongli