[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

pretty format arrays

Srijayanth Sridhar

4/15/2009 2:25:00 PM

[Note: parts of this message were removed to make it a legal post.]

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

2 Answers

Robert Klemme

4/15/2009 2:52:00 PM

0

2009/4/15 Srijayanth Sridhar <srijayanth@gmail.com>:
> 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=3D[London,Paris,NY.....=
].
> If printed in a single line it runs over and looks ugly. My hack so far i=
s:
>
> def pretty_print_list list,num=3D5
> =A0 a=3D[]
> =A0 (0...list.size).step(num) { |i| a << (list[i...i+num]).join(',') }
> =A0 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=3Do }
>
> The hack works fine, but on a broader subject, is there a nice easy way o=
f
> grouping arrays? In python Range accepts a step value which is quite
> awesome...

#each_slice does the job:

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

Cheers

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestprac...

Lyle Johnson

4/15/2009 2:59:00 PM

0

On Wed, Apr 15, 2009 at 9:24 AM, Srijayanth Sridhar
<srijayanth@gmail.com> 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