DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Acronym Builder

  • submit to reddit
        // Generates an acronym from a string. For example "Hello World Ruby SCrIpT" goes to "HWRS".

    acronym = ''
    bytes = [] # Byte array
    long_string = ' ' + long_string # so the first letter, if capital, is included
    long_string.each_byte {|byte| bytes.push(byte)} # Build array of bytes
    bytes.each_with_index do |byte, index|
      if byte > 64 and byte < 96 # This is the range for ASCII capital letters, your encoding may vary
        # Capital letter
        if bytes[index-1] == 32 # We check behind to see if the letter is preceded by a space. Again, encoding may vary. 32 is ASCII space.
          acronym = acronym + long_string[index,1]


Snippets Manager replied on Wed, 2007/05/16 - 11:08pm

Wow yeah, that is pretty monstrous. Hey, this is ruby, we can do even better: long_string.scan(/\b\w/)*'' If you want to only include capital letters instead of any word-beginning character (as the original script does) you can replace "\w" with "[A-Z]" above. Array of bytes! Kids these days.

Snippets Manager replied on Tue, 2008/03/04 - 12:34pm

What...?! What's wrong with simply: long_string.split(' ').map { |x| x.split('').first.upcase }.join Why would anyone use Ruby to code in C?!