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

Make Tuple#map_with_index return a Tuple. #5086

Merged
merged 1 commit into from
Oct 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Make Tuple#map_with_index return a Tuple.
  • Loading branch information
firejox committed Oct 7, 2017
commit 7d8b59246c446be6419455d1dca5c9b8d851dbd1
6 changes: 6 additions & 0 deletions spec/std/tuple_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,12 @@ describe "Tuple" do
tuple2.should eq({"1", "2.5", "a"})
end

it "does map_with_index" do
tuple = {1, 1, 2, 2}
tuple2 = tuple.map_with_index { |e, i| e + i }
tuple2.should eq({1, 2, 4, 5})
end

it "does reverse" do
{1, 2.5, "a", 'c'}.reverse.should eq({'c', "a", 2.5, 1})
end
Expand Down
16 changes: 16 additions & 0 deletions src/tuple.cr
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,22 @@ struct Tuple
{% end %}
end

# Like `map`, but the block gets passed both the element and its index.
#
# ```
# tuple = {1, 2.5, "a"}
# tuple.map_with_index { |e, i| "tuple[#{i}]: #{e}" } # => {"tuple[0]: 1", "tuple[1]: 2.5", "tuple[2]: a"}
# ```
def map_with_index
{% begin %}
Tuple.new(
{% for i in 0...T.size %}
(yield self[{{i}}], {{i}}),
{% end %}
)
{% end %}
end

# Returns a new tuple where the elements are in reverse order.
#
# ```
Expand Down