2014-10-10 54 views
0

我有下面的命令,它返回一個多行字符串,我想把它放到一個數組中,並迭代它,每行代表一個元素。array.each只返回Ruby中的第一個值

def get_mnt_pts 
`grep VolGroup /proc/self/mounts | awk '{print $2, $4}' | awk -F, '{print $1}' | awk '{print $1, $2}'` 
end 

該數據的命令返回並且是什麼輸入到陣列的原始看起來像分割之前

/ rw 
/home rw 
/usr rw 
/tmp rw 
/var rw 
/var/log rw 

我有下面的代碼看起來像它需要的數據和由換行拆分它並將其放入數組中。然後我調用數組的長度來確認,我可以提取N值,但是當我做array.each時,它只能捕獲第一個值。

我有一種感覺,我傾倒整個字符串作爲一個單一的元素,但然後.length返回我認爲應該。我已經通過數組和字符串檢查了Ruby文檔,看看我是否可以弄清楚。我很確定我創建的數組錯誤,但不知道如何。

mount_info = Array.new 
mount_info = get_mnt_pts.split("\n") 

puts mount_info.length #this returns 6 

mount_info.each do |pt| 
    puts pt #only puts the first value of/rw 
end 

當我打印出來mount_info本身,我得到以下

print mount_info 
["/ rw", "/home rw", "/usr rw", "/tmp rw", "/var rw", "/var/log rw"] 

puts mount_info 
/rw 
/home rw 
/usr rw 
/tmp rw 
/var rw 
/var/log rw 

print mount_info[4] #returns back /var rw 
puts mount_info[4] #returns back /var rw 

不知道在哪裏可以從這裏看,任何方向將是巨大的。最終的結果是,對於數組中的每個元素,我想嘗試在該目錄中寫入一個文件以確認文件系統實際上是可寫的。該數組包含一個掛載點的列表,並且對於每個掛載點,我將寫入一個Tempfile,以便下面的塊將包含在數組中並遍歷它。

def is_rw_test(mount_info) 
    mount_info.each do |pt| 
    Dir.exist? pt.split[0] || @crit_pt_test << "#{ pt.split[0] }" 
    file = Tempfile.new('.sensu', pt.split[0]) 
    puts "The temp file we are writing to is: #{ file.path }" if config[:debug] 
    file.write("mops") || @crit_pt_test << "#{ pt.split[0] }" 
    file.read || @crit_pt_test << "#{ pt.split[0] }" 
    file.close 
    file.unlink 
    return @crit_pt_test 
    end 
end 

代碼工作正常,但只對數組中的第一個元素,它不會對每個做,雖然,這就是爲什麼我認爲我的數組賦值是borked。

感謝

+1

你可以在數組中實際調用哪個代碼塊嗎? – bigtunacan 2014-10-10 13:16:51

回答

1
def is_rw_test(mount_info) 
    mount_info.each do |pt| 
    Dir.exist? pt.split[0] || @crit_pt_test << "#{ pt.split[0] }" 
    # Etc 
    return @crit_pt_test # ohai 
    end 
end 

你有一個return,所以它返回,並且通過each沒有更多的迭代。

如果你想收集值,然後做一些更接近:

def is_rw_test(mount_info) 
    mount_info.collect do |pt| 
    Dir.exist? pt.split[0] || @crit_pt_test << "#{ pt.split[0] }" 
    # Etc 
    @crit_pt_test 
    end 
end 

但是,如果是這樣的話那麼實例變量沒有任何意義。

你需要決定你實際想要什麼

+0

謝謝!我對Ruby相當陌生,所以我仍然在學習整個變種。大多數情況下,我最終都是用Ruby編寫Python代碼......並不是最好的主意! – Matty 2014-10-10 13:50:58