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
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
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
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
I'd do something like that :
def overview
[@a, @b].each do |e|
puts e.join("\n")
end
end