VirusHunter VirusHunter - 11 days ago 6
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
.each
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

You can use .map with .with_index:

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

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

Outputs:

1) a
2) b
3) c
Comments