Skip to content

Commit ebe683c

Browse files
firejoxRX14
authored andcommittedOct 7, 2017
Make Tuple#map_with_index return a Tuple. (#5086)
1 parent f0d609c commit ebe683c

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed
 

Diff for: ‎spec/std/tuple_spec.cr

+6
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,12 @@ describe "Tuple" do
210210
tuple2.should eq({"1", "2.5", "a"})
211211
end
212212

213+
it "does map_with_index" do
214+
tuple = {1, 1, 2, 2}
215+
tuple2 = tuple.map_with_index { |e, i| e + i }
216+
tuple2.should eq({1, 2, 4, 5})
217+
end
218+
213219
it "does reverse" do
214220
{1, 2.5, "a", 'c'}.reverse.should eq({'c', "a", 2.5, 1})
215221
end

Diff for: ‎src/tuple.cr

+16
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,22 @@ struct Tuple
408408
{% end %}
409409
end
410410

411+
# Like `map`, but the block gets passed both the element and its index.
412+
#
413+
# ```
414+
# tuple = {1, 2.5, "a"}
415+
# tuple.map_with_index { |e, i| "tuple[#{i}]: #{e}" } # => {"tuple[0]: 1", "tuple[1]: 2.5", "tuple[2]: a"}
416+
# ```
417+
def map_with_index
418+
{% begin %}
419+
Tuple.new(
420+
{% for i in 0...T.size %}
421+
(yield self[{{i}}], {{i}}),
422+
{% end %}
423+
)
424+
{% end %}
425+
end
426+
411427
# Returns a new tuple where the elements are in reverse order.
412428
#
413429
# ```

0 commit comments

Comments
 (0)
Please sign in to comment.