Skip to content

Commit

Permalink
Struct.new: check for duplicate members
Browse files Browse the repository at this point in the history
  • Loading branch information
XrXr committed Oct 29, 2019
1 parent 11a2d2c commit e71578c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
8 changes: 8 additions & 0 deletions spec/ruby/core/struct/new_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ def obj.to_str() "Foo" end
end
end

it "raises ArgumentError when there is a duplicate member" do
-> { Struct.new(:foo, :foo) }.should raise_error(ArgumentError, "duplicate member: foo")
end

it "raises a TypeError if object is not a Symbol" do
obj = mock(':ruby')
def obj.to_sym() :ruby end
Expand Down Expand Up @@ -156,6 +160,10 @@ def platform
obj.legs.should == 4
end

it "raises when there is a duplicate member" do
-> { Struct.new(:foo, :foo, keyword_init: true) }.should raise_error(ArgumentError, "duplicate member: foo")
end

describe "new class instantiation" do
it "accepts arguments as hash as well" do
obj = @struct_with_kwa.new({name: "elefant", legs: 4})
Expand Down
5 changes: 5 additions & 0 deletions src/main/ruby/truffleruby/core/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ def self.new(klass_name, *attrs, keyword_init: true, &block)
end
end

duplicates = attrs.uniq!
if duplicates
raise ArgumentError, "duplicate member: #{duplicates.first}"
end

klass = Class.new self do
_specialize attrs

Expand Down

0 comments on commit e71578c

Please sign in to comment.