0

I am new to the Language.

I am trying to extract all characters till the escape character (\r).

I tried

text = "abcde\r"

text.match(/(.*)(\r)/)

I tried the same with gsub and gsub!. None are working.

2
  • Where's the rest of your code? Commented Nov 21, 2014 at 18:45
  • \r isn't "the escape character", it's "an escaped character". Terminology is important. Commented Nov 21, 2014 at 20:58

2 Answers 2

2

If you happen to be dealing with the specific case of lines from a file, and you want to remove the line ending, you can use chop or chomp. For example:

require 'pp'

lines = [
  "hello",
  "there\r",
  "how\r\n",
  "are you?"
]

lines.each do |line|
  pp line
  pp line.chomp
  puts '---'
end

Results in:

"hello"
"hello"
---
"there\r"
"there"
---
"how\r\n"
"how"
---
"are you?"
"are you?"
---
Sign up to request clarification or add additional context in comments.

1 Comment

Be careful using chop as it indiscriminately removes the last character: 'foo'.chop # => "fo". Both rstrip and chomp are the most used ways to do this.
0

You can use String#slice passing the regular expression and the match to get. The 1 represents the first (and in this case the only) match.

text = "abcde\r"
text.slice(/(.*)\r/, 1)
 => "abcde" 

1 Comment

Thank you! Looks like I had issue with the irb terminal. It wasn't printing the output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.