Ruby Gets Possessive

Posted by code_monkey_steve on May 6, 2010 May 6

I debated whether this code snippet was significant enough to bother blogging about, but it is useful if for no other reason that as an example of one of the great features of Ruby: the ability to reopen any class, even a standard class, and add methods.

In this case, we needed a method to apply the English rules for the possessive apostrophy to a string, e.g. a person’s name. I looked-up the rules on Wikipedia and coded up the following three-liner:

{% highlight ruby }
class String
def possessive
str = self + “’”
str += ‘s’ unless %r{(s|se|z|ze|ce|x|xe)$}i.match(self)
str
end
end
{
endhighlight %}

Now in my site I can do things like:

{% highlight ruby }
“Steve”.possessive + " Profile" == “Steve’s Profile”
“Alex”.possessive + " Profile" == “Alex’ Profile”
{
endhighlight %}

(Cross-posted to the Conceivian Blog)