Reputation: 9457
I have a symbol like the following. Whenever the symbol contains the "-" hyphen mark, I want to remove it and upcase the subsequent letter. I am able to do it like so:
sym = :'new-york'
str = sym.to_s.capitalize
/-(.)/.match(str)
str = str.gsub(/-(.)/,$1.capitalize)
=> "NewYork"
This required four lines. Is there a more elegant way to create CamelCase (upper CamelCase e.g. NewYork, NewJersey, BucksCounty) from hyphened words in Ruby?
Upvotes: 0
Views: 129
Reputation: 110725
r = /
([[:alpha:]]+) # match 1 or more letters in capture group 1
- # match a hyphen
([[:alpha:]]+) # match 1 or more letters in capture group 2
/x # free-spacing regex definition mode
sym = :'new-york'
sym.to_s.sub(r) { $1.capitalize + $2.capitalize }
#=> "NewYork"
Upvotes: 0
Reputation: 121010
sym.to_s.gsub(/(-|\A)./) { $&[-1].upcase }
or
sym.to_s.gsub(/(-|\A)./) { |m| m[-1].upcase }
Upvotes: 0
Reputation: 9498
Here's one way:
sym.to_s.split('-').map(&:capitalize).join #=> "NewYork"
Upvotes: 4