H
H
HexUserHex2021-09-05 12:30:36
ruby
HexUserHex, 2021-09-05 12:30:36

Doesn't split string by delimiter in ruby ​​2.7.1p83?

It is required to split a string in ruby ​​on the separator "\"

Here is an example of a string:
Server username: DESKTOP-AHDESI\Username

Here's how I try:
user_name = "DESKTOP-AHDESI\Username"
print user_name.split("\\")

I get:
Ruby Error: NoMethodError undefined method `gsub!' for ["DESKTOP-AHDESIUsername"]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
N. Bekseitov, 2021-09-12
@nbekseitov

Slightly late answer:

  • In your case, to separate a string with a backslash, you need to put it in single quotes. Double quotes treat the backslash internally as a special character.
  • I don't know how you got the string, but the method returns it inside an array, which is why we get an error about gsub!. Use user_name.join or username.first to return the value as a normal string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question