Follow me on Twitter!

Dont Trust This Guy why not take my word for it? A blog by Jim Jeffers

Ruby: Extending classes and method chaining.

Once you start fooling around with the Ruby language you really do get hooked on just how powerful it is. I was disappointed when I first found out that the String.capitalize function only formatted the very first letter of a string to a capital letter as this is undesirable when you are formatting something like a street address. Not to worry though, extending the String class is easy in ruby and writing the function to do it requires only one line of code!

class String
  def capitalize_each
    self.split(" ").each{|word| word.capitalize!}.join(" ")
  end
  def capitalize_each!
    replace capitalize_each
  end
end

puts "hello WORLD!".capitalize_each #=> "Hello World!"

s = "6825 W. GALVESTON ST."
puts s.capitalize #=> "6825 w. galveston st."
puts s.capitalize_each #=> "6825 W. Galveston St."
puts s #=> "6825 W. GALVESTON ST."

s.capitalize_each!
puts s #=> "6825 W. Galveston St."

Pretty nifty eh? If any one can show me how to rewrite the function as a destructive function please comment because I’m stumped.

Update:

Thanks to Assaf’s comment I was able to write the destructive version of capitalize each.

3 Responses to This Article.

  1. assaf Says:

    Here…

    class String
      def capitalize_each!
        replace (split(" ").each{|word| word.capitalize!}.join(" "))
      end
    end
    
    str = "HELLO WORLD"
    puts str.capitalize_each!
    puts str
    
  2. Jim Says:

    Thanks Assaf I’m still an amateur in Ruby that one statement helped me a lot.

  3. vezult Says:

    Using self.replace in capitalize_each! rather than just replace would be a little more explicit. Additionally, it would match the style of your non-destructive method.

Leave a Reply

Meta Information

This post was filed under code and tagged with: , .

This Post as a Feed

The content of this post and it's comments can be subscribed to as an RSS feed.

DontTrustThisGuy.com and all contents copyright 2003-2007 by Jim Jeffers, unless otherwise noted.Written in valid XHTML and a participant of XFN while being powered by WordPress
Contents under Creative Commons License. Visual design, layout and Cascading Style Sheets may not be reused without permission.
Entries (RSS) and Comments (RSS)