Stripping dollar signs and commas from a string

Fri May 14 02:07:33 -0700 2010

It is moments like these that you realise why it is you love Ruby so much…

Today was one of those moments with the String class’s :delete method.

I have used this method many, many times in the past.. and this is nothing new for me… but it was one of those moments where I just went “Gee, I love coding in Ruby…” and I wanted to share :)

If you ever need to convert, say $12,345.12 into a single float number like 12345.12 a Ruby newbie, might do something like this:

"$12,345.12".gsub("$",'').gsub(",",'') #=> "12345.12"

But hark! Look into the string class and you shall find the :delete method, which lets you do this:

"$12,345.12".delete("$,") #=> "12345.12"

Ahhh… pure Ruby bliss.

blogLater

Mikel

  1. Sharad Says:

    If you are needing this for ActiveRecord attributes, you should also look at attribute-normalizer: http://github.com/mdeering/attribute_normalizer

  2. uorenshom Says:

    Your website is very useful for me , i like it very much, i get many informations from this !

  3. oil press machine Says:

    Your website is very useful for me , i like it very much, i get many informations from this !

Leave a Reply