2015-04-07 40 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"]