accessing index inside map

P

Peña, Botp

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
 
N

nobuyoshi nakada

Hi,

At Fri, 8 Jul 2005 16:30:22 +0900,
Pe=F1a, 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]

--=20
Nobu Nakada
 
D

daz

[...] 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
 
W

William Morgan

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top