2011-03-26 61 views
0

試圖映射的東西,我從文件中讀取到有一個整數和一個字符串數組的 列表分配映射陣列直接

它似乎不工作很正確,因爲我看到 兩個字符串每個數組,而不是一個整數 和一個字符串。

list_of_elems = [] 
File.foreach("line_counts.txt") do |line| 
    list_of_elems << arr = line.split(/\s+/).map! { |e, i| i == 0 ? e.to_i : e } 
end 

list_of_elems.each_with_index do |e, i| 
    if i > 10 
    break 
    end 
    p e 
end 
+0

代替你能給line_counts.txt的樣本線? – steenslag 2011-03-26 23:23:02

回答

0

您的問題是map!只傳遞一個參數的塊;因此i總是nil,i == 0總是失敗,並且to_i永遠不會被調用。我想你想要更多的東西是這樣的:

list_of_items = File.open('line_counts.txt').collect do |line| 
    line.split(/\s+/).inject([ ]) { |a, e| a.push(a.length == 0 ? e.to_i : e) } 
end 

a.length == 0基本上取代了你的錯誤i == 0檢查和該行的第一部分轉換爲整數。

如果linecounts.txt看起來是這樣的:

1 one 
2 two 

然後list_of_items最終看起來像這樣:

[[1, "one"], [2, "two"]] 

這似乎是你追求的。

1

如果我沒有理解好了,你想採取這樣的文件:

test 20 foo 
7 1 bar 6 

而得到這樣的:

[["test", 20, "foo"], 
[7, 1, "bar", 6]] 

,對嗎?

然後你可以使用:

list_of_elems = [] 
File.foreach("line_counts.txt") do |line| 
    list_of_elems << line.split(/\s+/).map {|e| e =~ /^(?:+|-)?\d+$/ ? e.to_i : e } 
end 

或者:

list_of_elems = File.read("line_counts.txt").split("\n").map do |line| 
    line.split(/\s+/).map {|e| e =~ /^(?:+|-)?\d+$/ ? e.to_i : e } 
end 
0

這應該工作太:

list_of_elems = File.foreach("line_counts.txt").map |line| 
    line.split.map.with_index { |e, i| i == 0 ? e.to_i : e } 
end 

我使用的地圖,而不是爲每個輸出,因爲你可以在TextMate中兩次打標籤,它構建塊給你。

list_of_elems.map { |e| puts e.to_s } 
1

這可能不是太相關,但是

list_of_elems.each_with_index do |e, i| 
    if i > 10 
    break 
    end 
    p e 
end 

可以

list_of_elems[0..10].each {|e| p e}