【问题标题】:Substracting string arrays in ruby在ruby中减去字符串数组
【发布时间】:2015-12-24 23:39:28
【问题描述】:

我有两个从 .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"]

我哪里错了?

【问题讨论】:

  • 嗨,欢迎来到堆栈溢出。你能告诉我们你用于 s1-s2 的确切代码吗? (这可能是一个小错字或其他什么,但除非您向我们展示,否则我们无法判断 :) (我问是因为我运行了该代码并且它对我来说非常有效)
  • 要么两个文件的内容相同,要么你将 2.txt 的内容都放在 s1 和 s2 中。
  • 错误似乎出在您未在此处显示的代码中。

标签: arrays ruby string subtraction


【解决方案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"]

但是请:仍然向我们展示您编写的代码,以便我们找出错误所在 - 否则您将永远学不会;)

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多