Ruby

From Jonathan Gardner's Tech Wiki

Jump to: navigation, search

Contents

Overview

My suggestion, learn Python instead. Really. Understanding both languages, that's my professional opinion.

Ruby is a language similar to perl or Python in many regards. It is, in a way, a Lisp-y, Python-y perl.

History

Ruby is unique in that it was first developed and popularized in Japan. I am sure early developers in the US found it fascinating to study a foreign language in a foreign language.

At the time, there wasn't any solid languages to fill the niche that Ruby tries to fill. If Python had been more mature back then, I am sure it would have been adopted.

Syntax

Programs

Programs consist of comments and expressions.

Comments

Comments begin with '#' and go to the end of the line. This is just like in Python, perl, and shell.

Ruby also has a POD-like syntax. Lines that begin with '=' mark the beginning of a documentation section, and lines beginning with '=end' end it.

Expressions

Expressions are terminated with semicolons or newlines. A backslash "\" at the end of the line continues the expression on the next line.

String Literals

String literals can be:

  • Surrounded by single quotes (')
  • Surrounded by double quotes (")
  • Started by %, followed by an optional "Q" or "q", then surrounded by any character that is not alphanumeric, even a newline. In the case of brackets, the opening bracket is on the left and the closing is on the right.

In other words, much like perl, except they use %, %q, or %Q instead of q and qq.

Double quoted strings are those with double quotes (") or % or %Q. These interpret the inside a little different than a literal.

Numeric literals

Identifiers

Identifiers are much like in C: [a-zA-Z_][a-zA-Z0-9_]

Reserved Words

The following words may not be identifiers.

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

Variables

  • Global variables start with '$' and are available everywhere in the program.
  • Instance variables start with '@'.
  • Constants start with an upper-case letter.
  • Special variables are "self", "nil", "true", "false", "__LINE__", and "__FILE__". These have different values depending on where they are executed.
  • All other variables are local variables.
Personal tools