Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 202
VirusHunter Avatar asked Nov 21 '16 17:11

VirusHunter


1 Answers

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
like image 128
Anthony Avatar answered Sep 19 '22 04:09

Anthony