One of the reasons I like writing in Ruby so much is because it is very capable of achieving a lot via one liners.
I like:
@sentence = @sentence.split(' ').map!{|x| x = x[0..0].upcase << x[1..-1] }.join(' ')
It capitalizes the first letter of each word, which is not the most stunning, but quite efficient.
What’s the most elegant one liner you have seen or written with Ruby?
You posted the oneliner:
But you misunderstand a couple things about Ruby.
First off, saying
x=in a map call doesn’t affect anything outside of the map call. The new value of that array element is the value returned by the block.Secondly, you don’t need to mutate the first string with
<<— a concatenation that creates a new string (using+) is a much better option.Thirdly,
map!makes changes directly to the array returned bysplit. What you want to do is leave that array untouched (even though it doesn’t change program semantics), and return a new array with the mapped results, by usingmap.So you should have written:
Now the statement
x[0..0].upcase + x[1..-1]is still very obtuse. Maybe you should replace it with thecapitalizemethod, which already changes the first letter of the string to uppercase. (Note that it also downcases all of the others, which may or may not be what you want.)I’d probably use
gsub!to change parts of the string in-place, but that’s probably a little obtuse:One more thing. If the only purpose of a block is to call a single method on the object passed to the block, you can do the following:
or to modify my
gsub!version: