【发布时间】:2018-07-23 04:07:00
【问题描述】:
我刚开始学习 ruby,但在用空格分隔字符串时遇到了麻烦。 首先,我读入我的文件并用换行符将它们分解:
inputfile = File.open("myfile.in")
filelines = inputfile.read.split("\n")
然后我尝试分别读取这两个数字中的每一个:
filelines.each_with_index {|val, index| do_something(val, index)}
其中do_something定义为:
def do_something(value, index)
if index == 0
numcases = value
puts numcases
else
value.split(" ")
puts value
puts value[0] #trying to access the first number
puts value[1] #trying to access the second number
end
end
但是对于像这样的较小的输入文件,
42
4 2
11 19
0 10
10 0
-10 0
0 -10
-76 -100
5 863
987 850
我的输出最终看起来像这样:
42
4 2
4
11 19
1
1
0 10
0
10 0
1
0
-10 0
-
1
0 -10
0
-76 -100
-
7
5 863
5
987 850
9
8
所以我的理解是它是逐个字符而不是按空格分解它。我知道它可以读取整行,因为我可以完整地打印数组的内容,但我不知道我做错了什么。 我也尝试将 value.split(" ") 替换为:
value.gsub(/\s+/m, ' ').strip.split(" ")
value.split
value.split("\s")
使用 RubyMine 2017.3.2
【问题讨论】:
-
试试
value = value.split(' ')。split不会改变它被调用的变量的值。 -
作为旁注,它看起来像是按字符拆分的原因是在 ruby 中,您可以像访问字符数组一样访问字符串。
"string"[1] #=> "t",您还可以使用范围和正则表达式与 String#[] -
另一个注意事项:如果你用
File.open打开一个没有块的文件,养成关闭它的习惯。inputfile.close会做到的。可以处理的打开文件数量有上限。