在ruby中提取字符串数组

时间:2015-12-24 23:39:29

标签: arrays ruby string subtraction

我有两个从.txt文件加载的字符串数组(s1和s2)

的1.txt

a
c
e

2.txt

b
d
e
使用

f = File.new(path, "r") #1.txt or 2.txt is passed in path
while (l = f.gets)
  res << l.chomp.downcase #just to be in the same case
end
f.close

我希望s1 - s2应该返回["a", "c"] 但 我得到["b", "d", "e"]

我哪里错了?

1 个答案:

答案 0 :(得分:1)

此代码适用于我:

# this reads out all the lines into the array-variable
# (no need for open/close/gets)
s1 = File.readlines("1.txt")
s2 = File.readlines("2.txt")

# now you want to chomp and downcase each one
# (the ! is important here or you lose the changes)
s1.map!{|l| l.chomp.downcase }
s2.map!{|l| l.chomp.downcase }

# now you can do a diff
s1 - s2

结果为:["a", "c"]

但是请:仍然向我们展示您编写的代码,以便我们可以弄清楚错误是什么 - 否则您将永远不会学习;)