Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are keywords defined in Ruby?

Tags:

ruby

I was looking at the Ruby documentation, and am wondering if everything is an object then 'keywords' are objects as well, correct? And if so, where are they defined in ruby?

The following page totally confused me caused it showed the object with all the keywords in it, however this is not the official Object that is used by all classes, is this mixed-in somehow from a different class??

http://ruby-doc.org/docs/keywords/1.9/Object.html

I guess there are lots of questions above, the main one is: how do ruby keywords get into ruby?

like image 624
Kamilski81 Avatar asked Feb 25 '12 17:02

Kamilski81


People also ask

Where is Puts defined in Ruby?

@Schwern If you want to see where puts is defined, you can simply do method(:puts). owner # => Kernel .

What are keywords in Ruby?

Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects or as constants. Doing this may result in compile-time error.

What is Def and end in Ruby?

The code def hi starts the definition of the method. It tells Ruby that we're defining a method, that its name is hi . The next line is the body of the method, the same line we saw earlier: puts "Hello World" . Finally, the last line end tells Ruby we're done defining the method.


1 Answers

The keywords are not objects but defined in the parser which can be found in parse.y in the Ruby source. Here's the relevant part from that file:

reswords    : keyword__LINE__ | keyword__FILE__ | keyword__ENCODING__
        | keyword_BEGIN | keyword_END
        | keyword_alias | keyword_and | keyword_begin
        | keyword_break | keyword_case | keyword_class | keyword_def
        | keyword_defined | keyword_do | keyword_else | keyword_elsif
        | keyword_end | keyword_ensure | keyword_false
        | keyword_for | keyword_in | keyword_module | keyword_next
        | keyword_nil | keyword_not | keyword_or | keyword_redo
        | keyword_rescue | keyword_retry | keyword_return | keyword_self
        | keyword_super | keyword_then | keyword_true | keyword_undef
        | keyword_when | keyword_yield | keyword_if | keyword_unless
        | keyword_while | keyword_until
        ;

If you want to know more about the Ruby parser, look at the presentation Hacking parse.y from RubyConf 2009 or Parse.y famtour from Ruby Kaigi 2011.

Also, a lot of the methods that are available everywhere (like e.g. puts) are defined in the Kernel module.

EDIT: There's also a list of key words in the documentation, thanks @antinome for pointing that out.

like image 62
Michael Kohl Avatar answered Oct 02 '22 13:10

Michael Kohl