tags:

views:

93

answers:

4

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
A: 

Just guess...

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
PeterWong
+7  A: 
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
mikej
But it uses more memory.
Hongli
is there a way to have at least a small label/tag for @a and @b printed? question answered in your second part! thanks!
poseid
Hongli's comment was posted before I expanded the answer with multiple suggestions. For clarity, he is referring to the use of `join` which will build a new string containing all the values.
mikej
'puts values.join("\n")' could be replaced by 'puts values'.
steenslag
+1  A: 

I'd do something like that :

def overview
    [@a, @b].each do |e|
        puts e.join("\n")
    end
end
Damien MATHIEU
+3  A: 
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
Hongli
'for f in ary; puts f; end' is unnecessary. Just 'puts ary' will do the job.
steenslag