Ruby Truncate String

In this blog post, we will learn how one can truncate the string in a ruby programming language. This problem is also popular as a ruby truncate string. By truncating we mean to cut a certain section of the string. In numeric values, this function rounds off the number to the specific number of decimal places. This function will cut the specific string after a certain number of characters. 

 

 

 

Solution of ruby truncate string

In ruby, we use a specific function called truncate to achieve this task. This function will take a number as an input parameter. This parameter means after which number we should truncate the string. The illustration for the same is also shown here:

 

 

'Once upon a time in a world far far away'.truncate(27)

 

The output of the same will be as shown below:

 

 

There is another way as well of solving the above problem but without using the concept of rails. 

 

 

text.gsub(/^(.{50,}?).*$/m,'\1...')

 

 

This will also give the same output as shown above. Rails here means repeating the same letter or character over and over multiple times. There is another method called truncate middle that also performs the same task. It takes starting and ending index values as the input. Here starting value shows the number by which we have to start truncating and the ending shows the end. 

 

 

 

Also Read: What is Convolutional Neural Network and Working

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *