1
Ruby 2.6

I have an variable (integer):

 num_rows = 7

I would like to turn it into an array of row numbers. I did:

rows_arr = []
num_rows = 5
i = 0
while i < num_rows
  rows_arr << "Row: #{i+1}"
  i += 1
end

which gives me:

=> ["Row: 1", "Row: 2", "Row: 3", "Row: 4", "Row: 5"]

Is there a cleaner, or more elegant, way of doing this?

3 Answers 3

4

You can do something like that:

num_rows=5
(1..num_rows).map { |n| "Row: #{n}" }
=> ["Row: 1", "Row: 2", "Row: 3", "Row: 4", "Row: 5"]
Sign up to request clarification or add additional context in comments.

Comments

1
nbr_rows = 5

["Row: "].product((1..nbr_rows).to_a).map(&:join)
  #["Row: 1", "Row: 2", "Row: 3", "Row: 4", "Row: 5"] 

The steps are as follows.

a = (1..nbr_rows).to_a
  #=> [1, 2, 3, 4, 5] 
b = ["Row: "].product(a)
  #=> [["Row: ", 1], ["Row: ", 2], ["Row: ", 3], ["Row: ", 4], ["Row: ", 5]] 
b.map(&:join)
  #=> ["Row: 1", "Row: 2", "Row: 3", "Row: 4", "Row: 5"] 

See Array#product and Array#join. Note that join converts the elements of a (integers) to strings.

This is just a different way to do it, using the oft-overlooked method Array#product. In practice I prefer @Constantin's solution, as I think it reads better.

1 Comment

Thank you for the explanation, I was not aware of the #Array#product method
1
   rows_arr = num_rows.times.map { |i| "Row: #{i + 1}" }

Comments

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.