【问题标题】:trouble with results of .split(" ") in RubyRuby 中 .split(" ") 的结果有问题
【发布时间】: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 会做到的。可以处理的打开文件数量有上限。

标签: arrays ruby parsing split


【解决方案1】:

正如在 cmets 中所说的那样,加上其他一些要点,带有一个惯用的代码示例:

lines = File.readlines('myfile.in')

header_line, data_lines = lines[0], lines[1..-1]

num_cases = header_line.to_i

arrays_of_number_strings = data_lines.map(&:split)
arrays_of_numbers = arrays_of_number_strings.map do |array_of_number_strings|
    array_of_number_strings.map(&:to_i)
end

puts "#{num_cases} cases in file."
arrays_of_numbers.each { |a| p a }
  • File.readlines 超级好用!
  • 我认为您没有在标题信息上调用 to_i, 会很重要。
  • data_lines.map(&:split) 将以字符串形式返回一个数字数组,但您还需要将这些字符串转换为数字。
  • 最后一行中的p a 将使用Array#inspect 方法,该方法便于将数组视为数组,例如[12, 34]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    相关资源
    最近更新 更多