Please help me change the elements in the array to [Element, Index]

Asked 2 years ago, Updated 2 years ago, 82 views

Arrangements such as ["hello", "ruby", "world"] in ruby

["Hello", [2], ["ruby", 3], [world", 4] How do I change it?

ruby array indexing

2022-09-22 21:59

1 Answers

1.9.3 and later can be created using Enumerator#with_index(offset=0).

Iterates the given block for each element with an index, which starts from offset. If no block is given, returns a new Enumerator that includes the index, starting from offset

[:a, :b, :c].map.with_index(2).to_a
#=> [[:a, 2], [:b, 3], [:c, 4]]

Enumerable#each_with_index(*args) { |obj, i| block }

Calls block with two arguments, the item and its index, for each item in enum. Given arguments are passed through to each().

arr.each_with_index.map { |x,i| [x, i+2] }


2022-09-22 21:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.