Skip to content

Commit 0c7d9c3

Browse files
committed
Add a type method for quick comparison
1 parent 81265ed commit 0c7d9c3

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

templates/lib/prism/node.rb.erb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,24 @@ module Prism
193193
<%- end -%>
194194
inspector.to_str
195195
end
196+
197+
# Sometimes you want to check an instance of a node against a list of
198+
# classes to see what kind of behavior to perform. Usually this is done by
199+
# calling `[cls1, cls2].include?(node.class)` or putting the node into a
200+
# case statement and doing `case node; when cls1; when cls2; end`. Both of
201+
# these approaches are relatively slow because of the constant lookups,
202+
# method calls, and/or array allocations.
203+
#
204+
# Instead, you can call #type, which will return to you a symbol that you
205+
# can use for comparison. This is faster than the other approaches because
206+
# it uses a single integer comparison, but also because if you're on CRuby
207+
# you can take advantage of the fact that case statements with all symbol
208+
# keys will use a jump table.
209+
#
210+
# def type: () -> Symbol
211+
def type
212+
:<%= node.human %>
213+
end
196214
end
197215
<%- end -%>
198216
<%- flags.each_with_index do |flag, flag_index| -%>

0 commit comments

Comments
 (0)