Ruby Programming/Syntax/Lexicology

(Redirected from Ruby Programming/Lexicology)

Identifiers edit

An identifier is a name used to identify a variable, method, or class.

As with most languages, valid identifiers consist of alphanumeric characters (A-Za-z0-9) and underscores (_), but may not begin with a digit (0-9). Additionally, identifiers that are method names may end with a question mark (?), exclamation point (!), or equal sign (=).

There are no arbitrary restrictions to the length of an identifier (i.e. it may be as long as you like, limited only by your computer's memory). Finally, there are reserved words which may not be used as identifiers.



Comments edit

Line comments run from a bare '#' character to the end of the line. Code commenting and documentation is best implemented with Ruby Embedded Documentation.


# this line does nothing; 
print "Hello" # this line prints "Hello"

Embedded Documentation edit


Everything between a line beginning with `=begin' down to
one beginning with `=end' will be skipped by the interpreter.
These reserved words must begin in column 1.

Reserved Words edit

The following words are reserved in Ruby:

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

You can find some examples of using them here.

Expressions edit


(1 + 2) * 3
if test then okay else not_good end

All variables, literals, control structures, etcetera are expressions. Using these together is called a program. You can divide expressions with newlines or semicolons (;) — however, a newline with a preceding backslash (\) is continued to the following line.

Since in Ruby control structures are expressions as well, one can do the following:

 foo = case 1
       when 1

The above equivalent in a language such as C would generate a syntax error since control structures are not expressions in the C language.