Programmatic way to get Ruby keywords

I have an Array in Ruby with all the keywords.

For instance:

RUBY_KEYWORDS = %w( alias and BEGIN begin break case class def defined do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield ) 

My question is simple:

Is there a built-in way to programmatically access all keywords?

Some of my projects have to run a query against user input, and it is a little annoying to define the same array in all of these projects.

+5
source share
2 answers

Try this code :)

 RubyToken::TokenDefinitions.select { |definition| definition[1] == RubyToken::TkId } .map { |definition| definition[2] } .compact .sort # returns : # ["BEGIN", "END", "__FILE__", "__LINE__", "alias", "and", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "end", "ensure", "false", "for", "if", "in", "module", "next", "nil", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield"] 
+6
source

I do not think you can, as it will be defined in the parser.

Your alternative is to look at the source code: https://github.com/ruby/ruby/blob/ruby_2_1/defs/keywords

0
source

Source: https://habr.com/ru/post/1210370/


All Articles