inchworm

inchworms

Summer of Coding, one inch at a time...

Reg Ex

inchworms -

Some more regular expression. And what for? To make BIG numbers more readable. For Example instead of 1234567 Euro we want to have 1’234’567 Euro. Wayyy better. So let’s write a helper method with a regex! Thanks to Arne we got it finally working:

def format_large_number(number)
    number.to_s.gsub(/\D/, '').reverse.gsub(/.{3}/, '\0\'').reverse.gsub(/^\'/, '')
end

The method takes the number and:

  • substitutes everything that’s not a number with nothing
  • reverses the number (7654321)
  • takes that and puts a ‘ every third position (765’432’1)
  • and reverses it again (1’234’567)
  • and in case we have a ‘ in the beginning, it substitutes it with nothing so we don’t get a ‘123’456

Piepe einfach (which translates as: easy peasy)

(Arne: In case I bungled the explanation, please contact me!)

xkcd