I want to truncate a string as follows:
input:
string = \"abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa ffffdffffdffffdffffddd\"
That's actually an interesting problem and you may want to solve it using javascript rather than ruby. Here is why, you're probably displaying this text on the screen somewhere, and you only have a certain amount of width available. So rather than having your link (or whatever text) cut down to a number of characters, what you really want is to make sure the text you're displaying never exceeds a certain width. How many characters can fit in a certain width depends on the font, spacing etc. (the css styles) you're using. You can make sure everything is ok if you're using a ruby-based solution, but it might all fall appart if you decide to change your styling later on.
So, I recommend a javascript-based solution. The way I've handled it previously has been to use the jquery truncate plugin. Include the plugin in your app. And then hook in some javascript similar to the following every time the page loads:
function truncateLongText() {
$('.my_style1').truncate({
width: 270,
addtitle: true
});
$('.my_style2').truncate({
width: 100
});
}
Add in whatever other styles need to be truncatable and the width that they should respect, the plugin does the rest. This has the added advantage of having all your truncation logic for the whole app in one place which can be handy.