truncate a string to first 200 characters

Discussion in 'Ruby' started by luke, Jul 9, 2005.

  1. luke

    luke Guest

    hi,

    i've been searching high and low for a method that will help me do this for
    a couple of days, but decided eventually just to post here in the hope
    someone can point out the probably blatantly obvious for me :)

    i'm looking for something that can take a string and truncate it to a
    certain amount of characters. then i can add '...' at the end.

    i used to use substr() when working with php

    $str = substr( $str, 0, 200) . "...";

    many thanks
    luke
     
    luke, Jul 9, 2005
    #1
    1. Advertisements

  2. luke

    daz Guest

    s = 'abcdefghijklmnopqrstuvwxyz'
    puts s[0, 6] << '...'

    #-> abcdef...


    daz
     
    daz, Jul 9, 2005
    #2
    1. Advertisements

  3. The most correct way of doing this IMHO is this:

    str += "..." if str.slice!(200 .. -1)

    which will cut away everything after the first 200 characters and append
    a marker if the string was truncated.

    Your PHP solution would map to this:

    str = str[0, 200] + "..."
     
    Florian Groß, Jul 9, 2005
    #3
  4. luke

    nobu.nokada Guest

    Hi,

    At Sat, 9 Jul 2005 12:25:50 +0900,
    daz wrote in [ruby-talk:147632]:
    If you consider multi-byte environments, you should strip
    trailing garbage bytes.

    puts s[0, 6][/\A.*/m] << '...'
     
    nobu.nokada, Jul 9, 2005
    #4
  5. luke

    luke Guest

    aaaah. i see. is this another case of 'everything is an object'? i need to
    wrap my head around the all pervasiveness of what that means in the future.
    thanks all.



     
    luke, Jul 9, 2005
    #5
  6. "blah".class #=> String

    From the command line:
    ri String#[]
    ri String#concat
    ri String#slice!

    Generally,
    ri String

    Devin
     
    Devin Mullins, Jul 9, 2005
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.