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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With