how can i access the index of the element inside the map argument block?
"101010,234,876".split(",").map {|c| get_something(c)}
...
All of the three solution taught me something. I think i'll go with .map.with_index.
That looks concise.
There is also the slightly less concise and elegant but possibly
somewhat faster:
ii = -1; "101010,234,876".split(",").map {|c| ii += 1; get_something(c)}
user system total real
Ruby: version=1.9.1; platform=i486-linux;
ary1 = ary.map.with_index { |e, i| 355 } 2.780 0.000 2.780 ( 2.787)
j = -1; ary2 = ary.map { |e| j += 1; 113 } 2.550 0.010 2.560 ( 2.556)
ary3 = ari.map!.with_index { |e, i| 355 } 2.590 0.000 2.590 ( 2.591)
j = -1; ary4 = arj.map! { |e| j += 1; 113 } 2.150 0.000 2.150 ( 2.150)
Ruby: version=1.9.1; platform=i386-mingw32;
ary1 = ary.map.with_index { |e, i| 355 } 2.870 0.000 2.870 ( 2.893)
j = -1; ary2 = ary.map { |e| j += 1; 113 } 2.028 0.016 2.044 ( 2.045)
ary3 = ari.map!.with_index { |e, i| 355 } 2.761 0.000 2.761 ( 2.772)
j = -1; ary4 = arj.map! { |e| j += 1; 113 } 1.997 0.000 1.997 ( 2.008)
*** code for benchmarks
class Array # so we can tell if same array and see changes
def ps( name = '?' )
puts "#{name}: <oid=#{object_id}: [0] = #{self[0].inspect}>"
end
end
require "benchmark"
kt = 100_000
nn = 100
ary = Array.new( nn, 42 )
ari = Array.new( nn, 22 ); arj = Array.new( nn, 7 )
puts
puts "Ruby: version=#{RUBY_VERSION}; platform=#{RUBY_PLATFORM};"
puts
ary.ps('ary'); ari.ps('ari'); arj.ps('arj')
puts
ary1 = ary2 = ary3 = ary4 = nil
w = 50
Benchmark.bmbm( w ) do |bm|
bm.report( "ary1 = ary.map.with_index { |e, i| 355 }" ) {
kt.times { ary1 = ary.map.with_index { |e, i| 355 } } }
bm.report( "j = -1; ary2 = ary.map { |e| j += 1; 113 }" ) {
kt.times { j = -1; ary2 = ary.map { |e| j += 1; 113 } } }
bm.report( "ary3 = ari.map!.with_index { |e, i| 355 }" ) {
kt.times { ary3 = ari.map!.with_index { |e, i| 355 } } }
bm.report( "j = -1; ary4 = arj.map! { |e| j += 1; 113 }" ) {
kt.times { j = -1; ary4 = arj.map! { |e| j += 1; 113 } } }
end
puts
ary.ps('ary'); ari.ps('ari'); arj.ps('arj')
puts
ary1.ps('ary1'); ary2.ps('ary2'); ary3.ps('ary3'); ary4.ps('ary4')