How to add "\n" in a string

str = “sunil kumar”

expected output: sunil\nkumar

You could try this

str = "sunil kumar".sub(/\s/, "\n")

Just extending @G4143’s answer, @sunilkumarnagoore can also use:

str = "sunil kumar"

str.gsub!(/.\s./, "\n")
# Or
str.gsub!(?\s, ?\n)
# Or
str.tr!(?\s, ?\n)

str    # => "sunil\nkumar"

For the methods, you can use either the bang (with ! at the end) method or the non bang version. The bang method modifies the original string, the non bang version (e.g., gsub, tr) doesn’t modify the original string, but create a complete new string each time…

1 Like

For the original poster… You should first start with Ruby’s irb(Ruby’s REPL). You can start the irb and enter

"".methods.sort

and it will list(in alphabetic order) any valid methods for strings. The irb is always a good starting point.

Kind of a round about way of doing it.

If you want to show /n inside the string without actually creating the new line just add the /n in the string and use single quotations.

Single quotations reads raw data.
Double quotations are used for intropolation and reads expressions added in the string.

print ‘hello \n world’
=> hello \n world
print “hello \n world”
=> hello
=> world

p also outputs raw data regardless of single or double quotations. and is used for debugging.

Intropolation:

str1 = ‘hello’
str2 = ‘world’
print “#{str1}” + ‘\n’ +"#{str2}"

Array
str = ‘hello world’.split
puts str.join(’\n’)

To remove items from a string you can use the .tr or .delete! Methods.

str = ‘hello \n world’.tr(’\n’ , ’ ')
or
str = 'hello \n world’s
str.delete! ‘\n’

.tr can modify the string too.

str = ‘hello world’.tr(‘hello’ , ‘goodbye’)