Accessing index inside map

#> how about
#>
#> # we only need the index
#> [1,2,3].each() {|i|* printf i,"\n"}
#>
#> # we need the val and the index
#> [1,2,3].each() {|x,i|* printf x,i,"\n"}
#>
#> # in other words, we always get the last param as the index
#> [[0,1],[1,2],[3,4]].each() {|x,y,i|* printf x,i,"\n"}
#>
#> ie, we put a star after the param delimiters || to signal an
#index. It's
#> like telling the programmer/reader "*hint-hint*"
#>

···

daz [mailto:dooby@d10.karoo.co.uk] wrote:

#
#[1].each { |n, i| x=n; p x } #-> 1
#[1].each { |n, i|* x=n; p x } #-> [1]

ouch! am i hopeless here ? :frowning:

how about we give more affinity to |n,i|* than to *x ? The spacing clearly
shows, right?

#
#Great care is needed when adding beyond the |bars| into code territory.
#But /no damage/ is caused by thinking aloud :slight_smile:

yes, thanks.

#
#For #each_with_index, the index is passed as a block parameter.
#That method has _two_ block parameters. That's probably why we
#expect to see the index there in an alternative implementation
#with the same result.
#
#[2].each { |n | p [n ] } #-> [2]
#[2].each_with_index { |n, index | p [n, index] } #-> [2, 0]
#
#Let's say that we were offered no choice of name and that an
#automatic block index were called $INDX.
#
#[2].meth { |n | p [n ] } #-> [2]
#[2].meth { |n | p [n, $INDX] } #-> [2, 0]
#
##meth passes _one_ argument and, regardless of whether or not
#we use the $INDX, it still only passes _one_ argument.
#'$INDX' isn't passed at all ... it's just ... /there/.
#

correct. a $ variable would be great also.
I'm not sure though how it will behave in nested loops or blocks though..

#IMPO, auto-index-naming wouldn't belong between the bars but I
#would be interested in hearing contrasting views.

imho, i treat blocks as just that, blocks. I do not want it to carry any
baggage coming fr outside, including the index. But that is just me.

#
#Your suggestion, correctly, highlights the problem that an extra
#block parameter, by itself, doesn't indicate to the parser that
#it's an index. Your extra '*' marker does that.

I couldn't think of any simple yet visible marker, so the star "*".

kind regards -botp

#
#Interesting.
#
#
#daz
#
#
#
#