Sometimes it makes me smile how things can be implemented in such a simple and beautiful way in Ruby.
We needed a method to return the length of the longest word in a string. So we opened up the String class and gave it a new toy to play with:
class String
# Returns the length of the longest word in the string
def longest_word_length
words = self.split(' ')
words.any? ? words.max{ |a,b| a.length <=> b.length }.length : 0
end
end
Of course, an RSpec example will keep our testing Yang intact!
describe String do
it "can determine the longest word in a string" do
"".longest_word_length.should eql(0)
"hello".longest_word_length.should eql(5)
"this is the longest word".longest_word_length.should eql(7)
"two words".longest_word_length.should eql(5)
"same size".longest_word_length.should eql(4)
end
end
Are there any little methods you have written that make you smile at their simplicity?
August 28, 2010 at 1:39 pm
[...] reading Ruby is beautiful – longest word length on my old blog… Tags beautiful, ruby, strings Categories [...]