简体   繁体   中英

create 2 d array with each_with_index

I am a newbie to Ruby. I am trying to creating a 2d array using each_with_index over an other array. ex:

arr = ["a","b","c"]
puts arr.each_with_index{|v,i| [v, i+1]}

But for some reason I see only 1d array.

a
b
c

instead of

a
1
b
2
c
3

Am I doing something wrong?

Probably not the best way, but for now this is one solution:

arr = ["a", "b", "c"]
new_arr = []

arr.each_with_index { |letter, idx| new_arr.push([letter, idx + 1])}

Here is another way:

arr = ["a", "b", "c"]
arr = arr.map.with_index { |el, idx| [el, idx + 1] }

Also note that using puts will print your statement with a new line. Using p will actually print out the object

Edit: And, I think I initially misunderstood your question. Luckily, the second method with map.with_index should be the one you're looking for. If you don't want to save the change, just don't set it with arr =

I would suggest:

arr.each.with_index(1).to_a
  #=> [["a", 1], ["b", 2], ["c", 3]] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM