Ruby is beautiful – longest word length

July 2, 2009 § Leave a comment

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?

Original post: Ruby is beautiful – longest word length.

Advertisements

Tagged: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Ruby is beautiful – longest word length at Fringley's Blog.

meta

%d bloggers like this: