Skip to content

Commit

Permalink
Make Tuple#map_with_index return a Tuple. (#5086)
Browse files Browse the repository at this point in the history
  • Loading branch information
firejox authored and RX14 committed Oct 7, 2017
1 parent f0d609c commit ebe683c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
6 changes: 6 additions & 0 deletions spec/std/tuple_spec.cr
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
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

0 comments on commit ebe683c

Please sign in to comment.