Jump to content

Ruby Programming/Syntax/Lexicology

From Wikibooks, open books for an open world

Identifiers

[edit | edit source]

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.

Examples:

foobar
ruby_is_simple

Comments

[edit | edit source]

Line comments run from a bare '#' character to the end of the line. Code commenting and documentation is best implemented with Ruby Embedded Documentation. http://www.ruby-doc.org/docs/ProgrammingRuby/html/rdtool.html

Examples:

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

Embedded Documentation

[edit | edit source]

Example:

=begin
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.
=end

Reserved Words

[edit | edit source]

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 | edit source]

Example:

true
(1 + 2) * 3
foo()
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
         true
       else
         false
       end

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