2012-08-29 66 views
0

嗨,我剛開始學習Ruby,我通過一個數組我創建看起來像這樣試圖循環:我如何在Ruby中循環數組?

server[0] = ['hostname' => 'unknown01', 'ip' => '192.168.0.2', 'port' => '22'] 
server[1] = ['hostname' => 'unknown02', 'ip' => '192.168.0.3', 'port' => '23'] 
server[2] = ['hostname' => 'unknown03', 'ip' => '192.168.0.4', 'port' => '24'] 

我嘗試使用此代碼:

i=0 
server[i].each do |x| 
    print x['hostname'] 
    print x['ip'] 
    i+=1 
end 

,但它只能通過服務器循環[0]我怎麼可以通過服務器循環[0-3]

回答

0

這可能不是你想象的那樣。既然你把你的鍵/值對放在方括號內,它就會變成一個哈希數組(其他語言稱之爲地圖和字典)。也許你想這樣用兩個大括號來交換你的方括號:

servers = [] 
servers[0] = {'hostname' => 'unknown01', 'ip' => '192.168.0.2', 'port' => '22'} 
servers[1] = {'hostname' => 'unknown02', 'ip' => '192.168.0.3', 'port' => '23'} 
servers[2] = {'hostname' => 'unknown03', 'ip' => '192.168.0.4', 'port' => '24'} 

但因爲你只是通過其索引設置每一個,你不需要建立起來這種方式,你可以到位他們在陣列中各自的位置。

servers.each do |server| 
    puts server['hostname'] 
    puts server['ip'] 
    puts 
end 

servers = [ 
    {'hostname' => 'unknown01', 'ip' => '192.168.0.2', 'port' => '22'}, 
    {'hostname' => 'unknown02', 'ip' => '192.168.0.3', 'port' => '23'}, 
    {'hostname' => 'unknown03', 'ip' => '192.168.0.4', 'port' => '24'}, 
] 

然後給每一個你可以做迭代

5

你並不需要使用i可言,只是這樣做:

server.each do |x| 
    print x['hostname'] 
    print x['ip'] 
end 
1

你在做什麼是將i設置爲0,所以當你到達server[i].each,你打電話server[0].each。即使你增加i,這不會改變你正在枚舉的內容。正確的代碼是:

server.each 

要枚舉server中的每個元素。