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"
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".
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.
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.
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)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With