Forum: Ruby pretty format arrays

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.
Srijayanth S. (Guest)
on 2009-04-15 18:25
(Received via mailing list)
Hello,

I am using OptionParser and one of the nifty things it has is multi line
descriptions for each option. I have a particularly long list of valid
arguments for a valid option, for instance
cities=[London,Paris,NY......].
If printed in a single line it runs over and looks ugly. My hack so far
is:

def pretty_print_list list,num=5
   a=[]
   (0...list.size).step(num) { |i| a << (list[i...i+num]).join(',') }
   a
end

This returns a list of strings which I pass as *list to the OptionParser
.on
method as follows:

arg.on("--city [CITY]",cities,*list) { |o| options.city=o }

The hack works fine, but on a broader subject, is there a nice easy way
of
grouping arrays? In python Range accepts a step value which is quite
awesome...

Thanks,

Jayanth
Robert K. (Guest)
on 2009-04-15 18:52
(Received via mailing list)
2009/4/15 Srijayanth S. <removed_email_address@domain.invalid>:
>   a
> end
>
> This returns a list of strings which I pass as *list to the OptionParser .on
> method as follows:
>
> arg.on("--city [CITY]",cities,*list) { |o| options.city=o }
>
> The hack works fine, but on a broader subject, is there a nice easy way of
> grouping arrays? In python Range accepts a step value which is quite
> awesome...

#each_slice does the job:

irb(main):008:0> a = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
irb(main):009:0> a.each_slice(3).to_a
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

Cheers

robert
Lyle J. (Guest)
on 2009-04-15 18:59
(Received via mailing list)
On Wed, Apr 15, 2009 at 9:24 AM, Srijayanth S.
<removed_email_address@domain.invalid> wrote:

> The hack works fine, but on a broader subject, is there a nice easy way of
> grouping arrays?

You could use Enumerator#each_slice:

    require 'enumerator'

    def pretty_print_list(list, num=5)
      a = []
      list.each_slice(5) {|s| a << s.join(",") }
      a
    end

Hope this helps,

Lyle
This topic is locked and can not be replied to.