sky
sky

Reputation: 13

Remove a ending character from each line on Ruby

So it reads from a online source file the string look like this,

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

So I only wants to put out the whole string with the ending "X" removed. In this example, only the X at the end of line 1 and line 4 will be removed. I used chomp, but it only removed the X in line4.

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

Should I use chomp or use something else?

Upvotes: 0

Views: 664

Answers (3)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

String#chomp will work if you change the record separator to include both your chosen character and a newline. For example:

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

The code above will print:

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

but it will still return the original string. This may or may not matter for your use case. If it does matter, then you may want to use Kernel#p and String#gsub instead. For example:

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"

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110675

Why not just use 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.

Upvotes: 1

mc-lunar
mc-lunar

Reputation: 293

Try this:

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

Upvotes: 1

Related Questions