Skip to content

Commit 0ac4374

Browse files
committed
[GR-19220] Fix Struct#inspect in anonymous classes/modules (#2870)
PullRequest: truffleruby/3655
2 parents a25f7df + 9fe1e5c commit 0ac4374

File tree

4 files changed

+25
-6
lines changed

4 files changed

+25
-6
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ Compatibility:
7979
* `Kernel#exit!`, killing Fibers and internal errors do not run code in `ensure` clauses anymore, the same as CRuby (@eregon).
8080
* Implement `UnboundMethod#original_name` (@paracycle, @nirvdrum).
8181
* Implement `Thread#native_thread_id` method (#2733, @horakivo).
82+
* Modify `Struct#{inspect,to_s}` to match MRI when the struct is nested inside of an anonymous class or module (@st0012, @nirvdrum).
8283

8384
Performance:
8485

spec/ruby/core/struct/inspect_spec.rb

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,5 @@
33
require_relative 'shared/inspect'
44

55
describe "Struct#inspect" do
6-
it "returns a string representation showing members and values" do
7-
car = StructClasses::Car.new('Ford', 'Ranger')
8-
car.inspect.should == '#<struct StructClasses::Car make="Ford", model="Ranger", year=nil>'
9-
end
10-
116
it_behaves_like :struct_inspect, :inspect
127
end
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,28 @@
11
describe :struct_inspect, shared: true do
2+
it "returns a string representation showing members and values" do
3+
car = StructClasses::Car.new('Ford', 'Ranger')
4+
car.send(@method).should == '#<struct StructClasses::Car make="Ford", model="Ranger", year=nil>'
5+
end
6+
27
it "returns a string representation without the class name for anonymous structs" do
38
Struct.new(:a).new("").send(@method).should == '#<struct a="">'
49
end
10+
11+
it "returns a string representation without the class name for structs nested in anonymous classes" do
12+
c = Class.new
13+
c.class_eval <<~DOC
14+
class Foo < Struct.new(:a); end
15+
DOC
16+
17+
c::Foo.new("").send(@method).should == '#<struct a="">'
18+
end
19+
20+
it "returns a string representation without the class name for structs nested in anonymous modules" do
21+
m = Module.new
22+
m.module_eval <<~DOC
23+
class Foo < Struct.new(:a); end
24+
DOC
25+
26+
m::Foo.new("").send(@method).should == '#<struct a="">'
27+
end
528
end

src/main/ruby/truffleruby/core/struct.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def to_s
147147

148148
name = self.class.name
149149

150-
if Primitive.nil?(name) || name.empty?
150+
if Primitive.nil?(name) || name.empty? || name[0] == '#'
151151
return "#<struct #{values.join(', ')}>"
152152
else
153153
return "#<struct #{self.class.name} #{values.join(', ')}>"

0 commit comments

Comments
 (0)