diff options
| author | Kevin Newton <kddnewton@gmail.com> | 2023-09-28 21:59:03 -0400 |
|---|---|---|
| committer | git <svn-admin@ruby-lang.org> | 2023-09-29 15:16:30 +0000 |
| commit | 100ce34331c40eed7039233a15d80e8efa5a1ac3 (patch) | |
| tree | 416fced2fb36fcf1b4590b49a4004f118a064c14 | |
| parent | 0d4c4b65733f1d6386dcf96ecd4605d752f66bba (diff) | |
[ruby/prism] Add a type method for quick comparison
https://github.com/ruby/prism/commit/0c7d9c3c01
| -rw-r--r-- | prism/templates/lib/prism/node.rb.erb | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/prism/templates/lib/prism/node.rb.erb b/prism/templates/lib/prism/node.rb.erb index 720d56b0df..f7937dc3e5 100644 --- a/prism/templates/lib/prism/node.rb.erb +++ b/prism/templates/lib/prism/node.rb.erb @@ -193,6 +193,24 @@ module Prism <%- end -%> inspector.to_str end + + # Sometimes you want to check an instance of a node against a list of + # classes to see what kind of behavior to perform. Usually this is done by + # calling `[cls1, cls2].include?(node.class)` or putting the node into a + # case statement and doing `case node; when cls1; when cls2; end`. Both of + # these approaches are relatively slow because of the constant lookups, + # method calls, and/or array allocations. + # + # Instead, you can call #type, which will return to you a symbol that you + # can use for comparison. This is faster than the other approaches because + # it uses a single integer comparison, but also because if you're on CRuby + # you can take advantage of the fact that case statements with all symbol + # keys will use a jump table. + # + # def type: () -> Symbol + def type + :<%= node.human %> + end end <%- end -%> <%- flags.each_with_index do |flag, flag_index| -%> |
