Accessing index inside map

Hi All,

How does one access the array index in #map?

eg,

irb(main):002:0> [1,2,3,4,5,6].map! {|x| x*2 }
=> [2, 4, 6, 8, 10, 12]

i'd like to double the element values except those loc on the 2nd and 5th
indices eg.

sorry if the answer is too obvious but i cannot find something like
array#each_with_index...

thanks in advance

kind regards -botp

Hi,

At Fri, 8 Jul 2005 16:30:22 +0900,
Peña, Botp wrote in [ruby-talk:147536]:

i'd like to double the element values except those loc on the 2nd and 5th
indices eg.

$ ruby -renumerator -e 'p (1..6).enum_for(:each_with_index).map{|x,i|[2,5].include?(i) ? x : x*2}'
[2, 4, 3, 8, 10, 6]

···

--
Nobu Nakada

Peña, Botp wrote:

[...] i cannot find something like array#each_with_index...

David Black was once President of Citizens for MWI, Inc.
(google "map with index" MWI).

Welcome!

You can add your own, of course.

module Enumerable
  def map_with_index!
    each_with_index do |e, ix|
      self[ix] = yield e, ix
    end
    self
  end
end

arr = (1..6).to_a
arr.map_with_index! do |e, ix|
  [2, 5].include?(ix) ? e : e*2
end

p arr
#=> [2, 4, 3, 8, 10, 6]

daz

Excerpts from daz's mail of 8 Jul 2005 (EDT):

David Black was once President of Citizens for MWI, Inc.
(google "map with index" MWI).

Welcome!

Count me as a member. I write this function approximately once for each
Ruby program I work on.

···

--
William <wmorgan-ruby-talk@masanjin.net>