VirusHunter VirusHunter - 1 year ago 72
Ruby Question

Turn a ruby array into a neat column string?

I'm new to ruby, and I'm trying to make a program that automates formatting for given strings and arrays. One autoformat function I'm trying to figure out is one for arrays. So let's say I have an array like the example below

myArray = ["a", "b", "c"]

and I want to turn it into a columnized string so that
puts myString
will give

`1) a`
`2) b`
`3) c`

How would I go about doing this? The closest thing I can find is using
which isn't what I want, I can't have each line a separate entry. It all has to be one string with line breaks.

Any help would be appreciated, thanks in advance

Answer Source

You can use .map with .with_index:

myArray = ["a", "b", "c"]

myStr = { |el, i| "#{i}) #{el}" }.join("\n")
puts myStr


1) a
2) b
3) c
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download