从Ruby上的每一行中删除一个结束字符

时间:2015-01-27 04:24:48

标签: ruby string

所以它从在线源文件中读取 字符串看起来像这样,

1. this is line1.X
2. this is "line2X"
3. this is X line4.
4. this is line3.X.X

所以我只想删除整个字符串,删除结尾“X”。在此示例中,仅删除第1行和第4行末尾的X. 我使用了chomp,但它只删除了第4行中的X.

string.each_line { |line| line.chomp("X") }

我应该使用chomp还是使用别的东西?

3 个答案:

答案 0 :(得分:1)

试试这个:

string.each_line { |line|
  if line[-1] = 'X'
    line.chop!
  end
}

答案 1 :(得分:1)

为什么不使用gsub

text =<<_
1. this is line1.X
2. this is "line2X"
3. this is X line4.
4. this is line3.X.X
_

puts text.gsub(/X$/,'')
  # 1. this is line1.
  # 2. this is "line2X"
  # 3. this is X line4.
  # 4. this is line3.X.

答案 2 :(得分:1)

如果您更改记录分隔符以包含所选字符换行符,则

String#chomp将起作用。例如:

string.each_line { |line| puts line.chomp("X\n") }

上面的代码将打印:

1. this is line1.
2. this is "line2X"
3. this is X line4.
4. this is line3.X.

但仍会返回原始字符串。这可能对您的用例有影响,也可能无关紧要。如果确实重要,那么您可能需要使用Kernel#pString#gsub。例如:

p string.gsub(/X$/, '')
#=> "1. this is line1.\n2. this is \"line2X\"\n3. this is X line4.\n4. this is line3.X.\n"

string
#=> "1. this is line1.X\n2. this is \"line2X\"\n3. this is X line4.\n4. this is line3.X.X\n"