Include ruby โ€‹โ€‹array in neat column row?

I'm new to ruby, and I'm trying to create 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 similar to the example below

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

and I want to turn it into a column row, so puts myString will give

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

How can I do it? The closest I can find is to use .each , which I donโ€™t want, I cannot have a separate entry on each line. All this should be one line with line breaks.

Any help would be appreciated, thanks in advance

+5
source share
1 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 
+9
source

Source: https://habr.com/ru/post/1260089/


All Articles