我目前正在处理大量名称:
large_array = ["Bob","Joel","John","Smith","Kevin","Will","Stanley","George"] #and so on
我把它分成子数组,如下所示:
large_array.each_slice(2).to_a #=> [["Bob", "Joel"],["John,"Smith"],["Kevin", "Will"],["Stanley","George"]]
我的问题是如何让子数组在这样的行中整齐地显示在彼此之上:
["Bob", "Joel"]
["John,"Smith"]
["Kevin","Will"]
["Stanley","George"]
答案 0 :(得分:2)
large_array.each_slice(2) {|a| puts a.inspect}
# ["Bob", "Joel"]
# ["John", "Smith"]
# ["Kevin", "Will"]
# ["Stanley", "George"]
# => nil
答案 1 :(得分:0)
你称之为"整洁"?这就是我所说的"整洁":
enum = large_array.each_slice(2)
fname_max = enum.map { |f,_| f.size }.max + 3
lname_max = enum.map { |_,l| l.size }.max + 1
enum.each { |f,l|
puts "[\"#{ (f+'",').ljust(fname_max) }\"#{ (l+'"').ljust(lname_max) }]" }
#-> ["Bob", "Joel" ]
# ["John", "Smith" ]
# ["Kevin", "Will" ]
# ["Stanley", "George"]
这是另一种编写"整洁":
的方式enum = large_array.to_enum
loop do
puts [enum.next, enum.next].to_s
end
#-> ["Bob", "Joel"]
# ["John", "Smith"]
# ["Kevin", "Will"]
# ["Stanley", "George"]
这适用于"大"数组,但对于"巨大的"数组(超过八个元素),您可能希望将操作行更改为:
puts [enum.next, enum.next].to_s.tinyfy
用于显示目的。这将打印以下内容:
["Bob", "Joel"] ["John", "Smith"] ["Kevin", "Will"] ["Stanley", "George"]