2015-04-07 43 views
0

我目前工作的一个大阵的名称上:配售子阵列

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

要打印它'stdout'或在任何文件? –

+0

我试图让它看起来像这样在irb – user1762229

+0

试试这个http://stackoverflow.com/questions/2112016/formatting-rubys-prettyprint –

回答

2
large_array.each_slice(2) {|a| puts a.inspect} 
# ["Bob", "Joel"] 
# ["John", "Smith"] 
# ["Kevin", "Will"] 
# ["Stanley", "George"] 
# => nil 
+0

当我运行它我得到你在那里的代码,但而不是零我也得到#=> [“鲍勃”,“乔尔”,“约翰”,“史密斯”,“凯文”,“将”,“斯坦利”,“乔治”]有没有办法摆脱那最后一个组合数组? @maerics – user1762229

+0

@ user1762229,是的,只需在语句结尾添加一个分号即可。 'large_array.each_slice(2){| a |放一个检查};'。 – Mori

+0

读者:'Array#to_s'是'Array#inspect'的别名。这可以写成'puts large_array.each_slice(2).map(&:inspect)',但是它有创建临时数组的缺点。 maerics,OP不希望收到'John'后的结束报价。 :-) –

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"] 

这工作得很好“大”数组,但对于“巨大的”阵列(更比8个元素),您可能希望将操作线更改为:

puts [enum.next, enum.next].to_s.tinyfy 

用于显示目的。这将打印以下内容:

 ["Bob", "Joel"] ["John", "Smith"] ["Kevin", "Will"] ["Stanley", "George"]