Skip to content

Commit

Permalink
Optimized version of Tuple#to_a (#8265)
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite authored Oct 3, 2019
1 parent e63f7fd commit 7a1112c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions spec/std/tuple_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -293,4 +293,13 @@ describe "Tuple" do
({/o+/, "bar"} === {"fox", "bar"}).should be_true
({1, 2} === nil).should be_false
end

it "does to_a" do
ary = {1, 'a', true}.to_a
ary.should eq([1, 'a', true])
ary.size.should eq(3)

ary = Tuple.new.to_a
ary.size.should eq(0)
end
end
9 changes: 9 additions & 0 deletions src/tuple.cr
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,15 @@ struct Tuple
to_s
end

def to_a
Array(Union(*T)).build(size) do |buffer|
{% for i in 0...T.size %}
buffer[{{i}}] = self[{{i}}]
{% end %}
size
end
end

# Appends a string representation of this tuple to the given `IO`.
#
# ```
Expand Down

0 comments on commit 7a1112c

Please sign in to comment.