Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic way to obtain Ruby keywords

Tags:

ruby

keyword

I have an Array in Ruby, with all 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 an in-built way to programmatically access all keywords?

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

like image 793
shevy Avatar asked Jan 04 '15 23:01

shevy


1 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"]
like image 104
romainsalles Avatar answered Nov 14 '22 21:11

romainsalles