In Ruby, why does "omega-3 (dHA)".gsub(/\b([a-z])/, '\0'.upcase) not work?
I want to capitalize the first character of each word and leave the rest intact (so it is different from Rails's titleize
, which downcase the rest). The first line is a test, and third line works, but I wonder why the second line doesn't work?
ruby-1.9.2-p180 :026 > "omega-3 (dHA)".gsub(/\b([a-z])/, '#\0#')
=> "#o#mega-3 (#d#HA)"
ruby-1.9.2-p180 :027 > "omega-3 (dHA)".gsub(/\b([a-z])/, '\0'.upcase)
=> "omega-3 (dHA)"
ruby-1.9.2-p180 :02开发者_JS百科8 > "omega-3 (dHA)".gsub(/\b([a-z])/) {|s| s.upcase}
=> "Omega-3 (DHA)"
'\0'.upcase
calls the upcase
method of the string '\0'
- parens for invokation are optional in Ruby. Which of course does nothing, so the second line is just .gsub(/.../, '\0')
精彩评论