5

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

1
  • What about this myArray.each_with_index.map {|i, j| "#{i+1}) #{j}"}.join("\n") Commented Nov 21, 2016 at 17:15

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

4 Comments

For OP's use case you'd want #{i+1}, but this is a great answer.
No worries. Your answer is quite elegant.
I think starting the index from 1 by using with_index(1) is better than doing i+1 in every iteration.
You don't need join here. puts myArray.map.with_index(1) { ... } will have the same result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.