How to change the default new line delimiter in Ruby

One of the core pillars of motivation is having the opportunity to use some form of autonomy at the work that you do. Ruby programming language allows you to do just that with a lot of its built-in features. It gives you the ability to override methods of basic built-in classes, methods and also attributes. One such attribute in which we will focus on this article is the ability to change the default new line delimiter.

It is almost like a convention to consider the phrase \n as a symbol notation of the new line in a string, as it starts with the first letter of new line. However, if you want to use \n for other purposes or simply want to use another character denoting the new line, then you have to change the global variable which Ruby uses to denote the new line in a string: $/. By default its value is set to \n, but we can change it to any other value of our choice:

$/ = “!”

That is pretty much all what you have to do. Here is an example:

$/ = “!”string =”Github!Quora!Wikipedia!Coursera”string.each_line { |element| p “Current line: ” + element}

The output of this will be

“Current line: Github!”“Current line: Quora!”“Current line: Wikipedia!”“Current line: Coursera”

If you are away from a machine that has Ruby already installed, you can try the example shown at this online IRB tool.

Note that this works only for interpolated strings (i.e. when you use double quotes for string objects), as the default new line notation \n.

Although you might find it intriguing and interesting to use this little trick, remember that it might not be a good idea to break the standard conventions unless it is necessary. Part of the reason for that is because most of the time we are working with other teammates in the same project and we do not want to waste their time figuring out the real meaning behind our lines of code.

Machine Learning Engineer | Let us connect on LinkedIn: