3 ms·
@sentence = @sentence.split(' ').map!{|x| x = x[0..0].upcase << x[1..-1]}.join(' ') Nobody sensible would write this code. The nearest sane version is: @s
by parenthephobia 11y ago
@sentence = @sentence.split(' ').map!{|x| x = x[0..0].upcase << x[1..-1]}.join(' ')
Nobody sensible would write this code. The nearest sane version is:
@sentence = @sentence.split(' ').map{|x| x[0].upcase + x[1..-1]}.join(' ')
But, although capitalize doesn't do the same thing, it's almost certainly what is actually wanted, so it would be
@sentence = @sentence.split(' ').map(&:capitalize).join(' ')
Having said that, it's much more likely that a "clever one-liner" would be
@sentence.gsub!(/\b\w/){|x|x.upcase}
Code like the article's would generally not be the result of cleverness, but of code that has organically mutated into something silly you'd never have written from scratch that way.
- brobinson 11y agoHuh, I've been doing Ruby since 2008 and I've never seen a block passed to gsub/gsub!. Neat! That said, a block isn't necessary here and the one-liner can be even shorter: @sentence.gsub!(/\b\w/, &:upcase) &: call syntax is actually a little faster post 1.9, too.