How to dry in Ruby?

How can I make this shorter and more extensible:

  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
+5
source share
4 answers
for f in @a
  puts f
end

can we write

puts @a.join("\n")

In general, when you want to do something with multiple arrays, you can put the arrays into an array and then use eachfor example.

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

and as soon as you start doing something more complicated than just printing the values, it makes sense to use refactoring the extraction method when performing the operation, for example.

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

, ( " " ..), :

{'As' => @a, 'Bs' => @b}.each_pair do |label, values|
    puts "All #{label}"
    puts values.join("\n")
end
+8
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
+4

- :

def overview
    [@a, @b].each do |e|
        puts e.join("\n")
    end
end
+1

...

def overview
  puts "All As:"
  puts_a(@a)
  puts "\n"

  puts "All Bs:"
  puts_a(@b)
end

def puts_a(strs)
  for str in strs
    puts str
  end
end
0
source

All Articles