Project

General

Profile

Feature #15730

Add map_with_index method

Added by jzakiya (Jabari Zakiya) 4 months ago. Updated 4 months ago.

Status:
Closed
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:92013]

Description

I was converting some Ruby code to Crystal on Rosetta Code and came across this Ruby snippet,

arry.each_with_index.map{ |x,y| ......}

where arry is an array of integers.

This wouldn't convert directly into Crystal (wouldn't compile).
Looking at their enumerables methods they have map_with_index, and that works.

arry.map_with_index{ |x,y| ......}

I don't know how frequently in Ruby this method combination exits, but I suspect it's somewhat common.
I think this method makes a whole lot of logical sense, would optimize the concept, and makes reading code easier.
Anyway, thanks for any consideration.

History

Updated by jeremyevans0 (Jeremy Evans) 4 months ago

jzakiya (Jabari Zakiya) wrote:

I was converting some Ruby code to Crystal on Rosetta Code and came across this Ruby snippet,

arry.each_with_index.map{ |x,y| ......}

where arry is an array of integers.

This wouldn't convert directly into Crystal (wouldn't compile).
Looking at their enumerables methods they have map_with_index, and that works.

arry.map_with_index{ |x,y| ......}

I don't know how frequently in Ruby this method combination exits, but I suspect it's somewhat common.
I think this method makes a whole lot of logical sense, would optimize the concept, and makes reading code easier.
Anyway, thanks for any consideration.

Enumerator#with_index already exists:

 [1,3,5].map.with_index{ |x, i| (x+i)**2}
=> [1, 16, 49]

I believe the reason Enumerable#each_with_index is a separate method is because it was added before Enumerator#with_index. However, I don't think it makes sense to add more *_with_index methods.

Updated by shevegen (Robert A. Heiler) 4 months ago

I do not have any particularly strong opinion either way. Jabari has made one point,
though, independent of crystal, in that it may make sense to have a corresponding
.map_with_index if .each_with_index exists already. But I think ultimately this
is where matz just has to decide on how he thinks ruby users should use ruby
in general; one can always take the even simpler approach and say that ruby
users should only use method chaining, such as .each.with_index or .map.with_index,
but I think one argument in the past, if we tap into older discussions, such as
.flat_map versus .map.flatten, was that the former is considerably faster than
the latter. So speed consideration may have been a primary reason for the addition
of this, and perhaps other methods - but I am not sure if that was the case. The
core team may know this better than I do.

As said, though, I am fine either way really so I have no particular opinion
on the suggestion as such.

Updated by matz (Yukihiro Matsumoto) 4 months ago

  • Status changed from Open to Closed

Use map.with_index.

Matz.

Also available in: Atom PDF