Can you better this String acronym method?


#1

Can you better this String acronym method?

def acronym name
letters=[]
name.each_char {|char| letters<<char if char[0]>=65 and char[0]<=90}
acronym = letters.join " "
end

chris


#2

are you trying to strip out all non capitalized alpha characters from a
string?

if so, just use a regular expression

replace anything that is not a capital letter A-Z with a blank

acronym = “Here Is A String”.gsub(/[^A-Z]/, ‘’) # => HIAS


#3

Good tries but wrong, i’m just trying to get an acronym from a string.

so

“help me please”.acronym # => “HMP”
or
“Help oUr kinGS”.acronym # => “HOK”

Thanks


#4

Hi –

On Tue, 14 Mar 2006, Chris wrote:

Can you better this String acronym method?

def acronym name
letters=[]
name.each_char {|char| letters<<char if char[0]>=65 and char[0]<=90}
acronym = letters.join " "
end

How about:

def acronym(name)
name.scan(/[[:upper:]]/).join(" ")
end

David


David A. Black (removed_email_address@domain.invalid)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

“Ruby for Rails” chapters now available
from Manning Early Access Program! http://www.manning.com/books/black


#5

Chris wrote:

Good tries but wrong, i’m just trying to get an acronym from a string.

so

“help me please”.acronym # => “HMP”
or
“Help oUr kinGS”.acronym # => “HOK”
“Help oUr kinGS”.scan(/(\A|\W)(\w)/).collect{|s| s[1]}.join.upcase


#6

I really appreciate that Alex,thanks.

What about if i wanted a space inbetween each letter? like so :

“Help oUr kinGS”.acronym # => “H O K”

Thanks :slight_smile:


#7

Alex Y. wrote:

“Help oUr kinGS”.scan(/(\A|\W)(\w)/).collect{|s| s[1]}.join.upcase
Better:
“help our kings”.gsub(/(\w)\w+\W*/, ‘\1’).upcase


#8

Chris wrote:

I really appreciate that Alex,thanks.

What about if i wanted a space inbetween each letter? like so :

“Help oUr kinGS”.acronym # => “H O K”

Thanks :slight_smile:

“help our kings”.gsub(/(\w)\w+\W*/, '\1 ').upcase.strip


#9

Hi –

On Wed, 15 Mar 2006, Chris wrote:

Good tries but wrong, i’m just trying to get an acronym from a string.

so

“help me please”.acronym # => “HMP”
or
“Help oUr kinGS”.acronym # => “HOK”

I was assuming you wanted code that worked the way your code did. I
guess not :slight_smile:

How about this:

def acronym(string)
string.scan(/\b\w/).join.upcase
end

(or put it in String class if you wish)

David


David A. Black (removed_email_address@domain.invalid)
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)

“Ruby for Rails” chapters now available
from Manning Early Access Program! http://www.manning.com/books/black


#10

What about if i wanted a space inbetween each letter? like so :

str.scan(/\w+/).collect { |w| w[0].chr }.join(myseparator).upcase

seems to work for me (put whatever you need in myseparator)