Ruby Programming Language Features Tutorial
The following is a list of features of the Ruby Programming Language
- object-oriented
- four levels of variable scope: global, class, instance, and local
- exception handling
- iterators and closures (based on passing blocks of code)
- native, Perl-like regular expressions at the language level
- operator overloading
- automatic garbage collecting
- highly portable
- cooperative multi-threading on all platforms using green threads
- DLL/shared library dynamic loading on most platforms
- introspection, reflection and meta-programming
- large standard library
- supports dependency injection
- continuations and generators (examples in RubyGarden: continuations and generators)
Ruby Interaction
The Ruby official distribution also includes "irb", an interactive command-line interpreter which can be used to test code quickly. A session with this interactive program might be:
$ irb
irb(main):001:0> puts "Hello, World"
Hello, World
=> nil
irb(main):002:0> 1+2
=> 3
There also exist readline bindings (module Readline), easily allowing the user for custom shells with history support.
About the Ruby Syntax
The syntax of Ruby is broadly similar to Perl and Python. Class and method definitions are signaled by keywords. In contrast to Perl, variables are not obligatorily prefixed with a sigil. (When used, the sigil changes the semantics of scope of the variable.) The most striking difference from C and Perl is that keywords are typically used to define logical code blocks, without brackets. Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Indentation is not significant (unlike Python).
Gotchas and possible surprises
Although Ruby's design is guided by the principle of least surprise, naturally, some features differ from languages such as C or Perl:
- Names that begin with a capital letter are treated as constants, so local variables should begin with a lowercase letter.
- To denote floating point numbers, one must follow with a zero digit (99.0) or an explicit conversion (99.to_f). It is insufficient to append a dot (99.) because numbers are susceptible to method syntax.
- Boolean evaluation of non-boolean data is strict: 0, "" and [] are all evaluated to true. In C, the expression 0 ? 1 : 0 evaluates to 0 (i.e. false). In Ruby, however, it yields 1, as all numbers evaluate to true; only nil and false evaluate to false. A corollary to this rule is that Ruby methods by convention — for example, regular-expression searches — return numbers, strings, lists, or other non-false values on success, but nil on failure (e.g., mismatch). This convention is also used in Smalltalk, where however only the special objects true and false can be used in a boolean expression.
- Versions prior to 1.9 lack a character data type (compare to C, which provides type char for characters). This may cause surprises when slicing strings: "abc"[0] yields 97 (an integer, representing the ASCII code of the first character in the string); to obtain "a" use "abc"[0,1] (a substring of length 1) or "abc"[0].chr.
In addition, some issues with the language itself are commonly raised:
- In terms of speed, Ruby's performance is inferior to that of many compiled languages (as is any interpreted language) and other major scripting languages such as Python and Perl[4]. However, in future releases (current revision: 1.9), Ruby will be bytecode compiled to be executed on the YARV (Yet Another Ruby VM). Currently, Ruby's memory footprint for the same operations is better than Perl's and Python's.
- Omission of parentheses around method arguments may lead to unexpected results if the methods take multiple parameters. Note that the Ruby developers have stated that omission of parentheses on multi-parameter methods may be disallowed in future Ruby versions. Much existing literature, however, encourages parenthesis omission for single-argument methods.
Ruby differs from Python in how it treats named arguments in function invocation: in Ruby, C, and many other languages, calling a function by some_function(x=4, 5) binds x to 4, and passes 4 and 5 to some_function. In Python, however, this would behave differently; the argument named x in the function definition for some_function would have 4 passed to it, and 5 would be passed into the remaining argument, this all being regardless of the order of arguments.
A good list of "gotchas" may be found in Hal Fulton's book The Ruby Way, pages 48-64 (ISBN 0-672-32884-4). However, since the list in the book pertains to an older version of Ruby (version 1.6), some items have been fixed since the book's publication. For example, retry now works with while, until and for, as well as iterators.
Ruby Syntax Tutorial Code Examples
Ruby Puts Syntax Example
puts "Hello World!"
Basic Ruby Syntax Code
# Everything, including a literal, is an object, so this works:
-199.abs # 199
"ruby is cool".length # 12
"Rick".index("c") # 2
"Nice Day Isn't It?".split(//).uniq.sort.join # " '?DINaceinsty"
Using an Array
a = [1, 'hi', 3.14, 1, 2, [4, 5]]
a[2] # 3.14
a.reverse # [[4, 5], 2, 1, 3.14, 'hi', 1]
a.flatten.uniq # [1, 'hi', 3.14, 2, 4, 5]
Constructing and Using a Hash
hash = {:water => 'wet', :fire => 'hot'}
puts hash[:fire] # Prints: hot
hash.each_pair do |key, value| # Or: hash.each do |key, value|
puts "#{key} is #{value}"
end
# Prints: water is wet
# fire is hot
hash.delete_if {|key, value| key == :water}
# Deletes :water => 'wet'
That's going to do it for the tutorial for Ruby, make sure you head over to the Ruby on Rails Tutorial Section