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
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
are you trying to strip out all non capitalized alpha characters from a
string?
if so, just use a regular expression
acronym = “Here Is A String”.gsub(/[^A-Z]/, ‘’) # => HIAS
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
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 ([email protected])
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)
“Ruby for Rails” chapters now available
from Manning Early Access Program! Ruby for Rails
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
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
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
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
“help our kings”.gsub(/(\w)\w+\W*/, '\1 ').upcase.strip
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
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 ([email protected])
Ruby Power and Light, LLC (http://www.rubypowerandlight.com)
“Ruby for Rails” chapters now available
from Manning Early Access Program! Ruby for Rails
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)
Hey Chris!
You can use this
text.scan(/\b\w/).join.upcase
I’m going to apply it in your code
def acronym name
name.scan(/\b\w/).join.upcase
end
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs