배열에 원소를 [원소, 인덱스]로 바꾸는거 도와주세요
조회수 1611회
발생하는 문제 및 실행환경
ruby에서 ["hello", "ruby", "world"] 같은 배열을
[["hello",2], ["ruby",3], ["world",4]] 로 바꾸려면 어떻게 쓰나요?
1 답변
-
with_index
1.9.3이상에서는 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]]
each_with_index
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] }
댓글 입력