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
Acronym Builder
// 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]
end
end
end






Comments
Snippets Manager replied on Wed, 2007/05/16 - 11:08pm
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
long_string.split(' ').map { |x| x.split('').first.upcase }.joinWhy would anyone use Ruby to code in C?!