Ruby 直接分配映射数组
试图将我从文件中读取的内容映射到 包含整数和字符串的数组列表 这似乎不太对劲,因为我明白了 每个数组两个字符串,而不是一个整数 还有一根绳子Ruby 直接分配映射数组,ruby,Ruby,试图将我从文件中读取的内容映射到 包含整数和字符串的数组列表 这似乎不太对劲,因为我明白了 每个数组两个字符串,而不是一个整数 还有一根绳子 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_inde
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
元素列表=[]
File.foreach(“line_counts.txt”)do | line|
要素清单10
打破
结束
体育课
结束
如果我理解得很好,您想要这样的文件:
test 20 foo
7 1 bar 6
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
1 one
2 two
[[1, "one"], [2, "two"]]
得到这个:
[["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
您的问题是,只将一个参数传递给块;因此,i
总是nil
,i==0
总是失败,并且从不调用to_i
。我想你想要更像这样的东西:
test 20 foo
7 1 bar 6
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
1 one
2 two
[[1, "one"], [2, "two"]]
a.length==0
基本上替换了错误的i==0
检查,并将行的第一个分量转换为整数
如果linecounts.txt
如下所示:
test 20 foo
7 1 bar 6
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
1 one
2 two
[[1, "one"], [2, "two"]]
然后,项目列表
的结果如下:
test 20 foo
7 1 bar 6
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
1 one
2 two
[[1, "one"], [2, "two"]]
这似乎就是你想要的。这也应该有效:
list_of_elems = File.foreach("line_counts.txt").map |line|
line.split.map.with_index { |e, i| i == 0 ? e.to_i : e }
end
我对输出使用map而不是each,因为您可以在textmate中按两次tab,它会为您构建块
list_of_elems.map { |e| puts e.to_s }
这可能不太相关,但是
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}
你能给我一行样本吗?