Skip to content

Commit f6910ff

Browse files
charlesluzarjoeldrapperixti
authored
Change behavior of Enum's to_s and to_sym methods (#326)
This changes the behavior of `to_s` and `to_sym` on Enums. `to_s` returns a humanized version of the demodularized class name, eg: "Red," "Slate gray," "Spring green" `to_sym` converts the demodularized class name to a symbol, eg: `:Red`, `:SlateGray`, `:SPRING_GREEN` Note that this was deemed a minor breaking change. --------- Co-authored-by: Joel Drapper <[email protected]> Co-authored-by: Alexey Zapparov <[email protected]>
1 parent b96277c commit f6910ff

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

lib/literal/enum.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,14 @@ def name
199199
end
200200

201201
alias_method :inspect, :name
202-
alias_method :to_s, :name
202+
203+
def to_sym
204+
self.class.names[self]
205+
end
206+
207+
def to_s
208+
to_sym.to_s
209+
end
203210

204211
def deconstruct
205212
[@value]

test/enum.test.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,20 @@ class SymbolTypedEnum < Literal::Enum(Symbol)
130130
]
131131
end
132132

133+
test ".to_s" do
134+
assert_equal Color::Red.to_s, "Red"
135+
assert_equal Color::SPRING_GREEN.to_s, "SPRING_GREEN"
136+
assert_equal Switch::On.to_s, "On"
137+
assert_equal SymbolTypedEnum::A.to_s, "A"
138+
end
139+
140+
test ".to_sym" do
141+
assert_equal Color::Red.to_sym, :Red
142+
assert_equal Color::SPRING_GREEN.to_sym, :SPRING_GREEN
143+
assert_equal Switch::On.to_sym, :On
144+
assert_equal SymbolTypedEnum::A.to_sym, :A
145+
end
146+
133147
test "#succ" do
134148
assert_equal Color::Red.succ, Color::Green
135149
assert_equal Color::Green.succ, Color::Blue

0 commit comments

Comments
 (0)