Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Enumerable#select_with_index, Enumerable#reject_with_index #3869

Closed

Conversation

upamune
Copy link

@upamune upamune commented Jan 11, 2017

Hi ✋

I added two methods into Enumerable .

@upamune upamune force-pushed the feature/select-reject-with-index branch from c61faa6 to bcb7b11 Compare January 11, 2017 01:07
@yxhuvud
Copy link
Contributor

yxhuvud commented Jan 11, 2017

Adding _with_index-variants of each and every iterator seems like a combinatoric hell. If the .with_index iterator isn't good enough, are there any reasons we couldn't improve that one instead?

@upamune
Copy link
Author

upamune commented Jan 11, 2017

I was convinced that there was no ′with_index′ method. There is no problem if there is a ′with_index′ method. Thank you very much. This pull request will close.

@upamune upamune closed this Jan 11, 2017
@mverzilli
Copy link

mverzilli commented Jan 11, 2017

I was about to make exactly the same remark as @yxhuvud. In Ruby you can do:

["a","b","c","d"].reject.each_with_index{|elem, index| index.even? }

In Crystal it'd be cool if we could do:

["a","b","c","d"].reject.with_index{|elem, index| index.even? }

But currently it doesn't work because there's no overload of select that doesn't receive a block. That would be a nice addition to the std :).

@ysbaddaden
Copy link
Contributor

This is achievable with iterators, but still complex:

["a", "b", "c", "d"]
  .each                      # start iterator
  .with_index                # add index
  .reject { |(c, i)| i < 2 } # filter
  .map(&.first)              # get rid of index
  .to_a                      # execute

It can be simplified, but that requires a manual filter:

["a", "b", "c", "d"]
  .each_with_index                         # start iterator + add index
  .compact_map { |(c, i)| c unless i < 2 } # manual filter + skip nils
  .to_a                                    # execute

I'm not fond of adding lots of *_with_index methods, but it would still be the most elegant:

["a", "b", "c", "d"]
  .reject_with_index { |c, i| i < 2 } # self explanatory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants