Forum: Ruby ,elegant

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
467c7c87ad5b36859a7644b9198b490a?d=identicon&s=25 Leslie Viljoen (Guest)
on 2005-12-13 18:27
(Received via mailing list)
Hiya!

This function adds commas to a string after every three characters
so a number would be easier to read. It's kinda ugly though, and I can't
help thinking there'd be a elegant Why-esque one or two liner to do
this kind of thing - anyone care to improve it?


def add_commas(str)
  return nil if str.class != String

  ret = ""
  len = str.length
  i = len - 1
  while i >= 0
    ret = str[i].chr + ret
    if ((len-i) % 3) == 0
      ret = "," + ret
    end
    i -= 1
  end
  if ret[0].chr == ","
    ret = ret[1..-1]
  end
  ret
end
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2005-12-13 18:42
(Received via mailing list)
On Dec 13, 2005, at 11:24 AM, Leslie Viljoen wrote:

> Hiya!
>
> This function adds commas to a string after every three characters
> so a number would be easier to read. It's kinda ugly though, and I
> can't
> help thinking there'd be a elegant Why-esque one or two liner to do
> this kind of thing - anyone care to improve it?

Does this help?

http://rubyurl.com/EOi

James Edward Gray II
467c7c87ad5b36859a7644b9198b490a?d=identicon&s=25 Leslie Viljoen (Guest)
on 2005-12-13 18:48
(Received via mailing list)
James Edward Gray II wrote:

>
> Does this help?
>
> http://rubyurl.com/EOi
>
> James Edward Gray II
>
I knew it! This kind of thing makes me crazy! I used to think I was a
good programmer!
Cb48ca5059faf7409a5ab3745a964696?d=identicon&s=25 unknown (Guest)
on 2005-12-13 19:00
(Received via mailing list)
On Wed, 14 Dec 2005, Leslie Viljoen wrote:

>
> if ret[0].chr == ","
>   ret = ret[1..-1]
> end
> ret
> end

   harp:~ > cat a.rb
   def commafy s
     s.to_s.reverse.scan(%r/.{1,3}/).join(',').reverse
   end

   p(commafy(''))
   p(commafy('4'))
   p(commafy('42'))
   p(commafy('422'))
   p(commafy('4242'))
   p(commafy('42424'))
   p(commafy('424242'))
   p(commafy('4242424'))

   harp:~ > ruby a.rb
   ""
   "4"
   "42"
   "422"
   "4,242"
   "42,424"
   "424,242"
   "4,242,424"

if you want you can play with the pattern so the two reverses aren't
needed...
but this is quicker to write ;-)

-a
This topic is locked and can not be replied to.