Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate string with Rails?

I want to truncate a string as follows:

input:

string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa dddddddddddddd" 

output:

string = "abcd asfsa sadfsaf safsdaf aa...ddddd" 
like image 427
krunal shah Avatar asked Aug 11 '11 09:08

krunal shah


People also ask

What is truncate in rails?

Method: String#truncateTruncates a given text after a given length if text is longer than length : "Once upon a time in a world far far away". truncate(27) # => "Once upon a time in a wo..." Pass a :separator to truncate text at a natural break: "Once upon a time in a world far far away".

What is truncate in Ruby?

The truncate() is an inbuilt method in Ruby returns a number rounded toward zero with a precision of the given number of digits after the decimal point. In case the number of digits is not given, the default value is taken to be zero.

How do I remove a character from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.


1 Answers

Take a look at truncate, it partially does want you want. If you test whether it got trunctated or not, you could add some of the last part back after the truncated part.

truncate("Once upon a time in a world far far away") # => "Once upon a time in a world..."  truncate("Once upon a time in a world far far away", :length => 17) # => "Once upon a ti..."  truncate("Once upon a time in a world far far away", :length => 17, :separator => ' ') # => "Once upon a..."  truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)') # => "And they f... (continued)" 
like image 87
Veger Avatar answered Oct 06 '22 19:10

Veger