Ruby programming language
From open-encyclopedia.com - the free encyclopedia.
Ruby is an object-oriented programming language. It combines syntax inspired by Ada and Perl with Smalltalk-like object oriented features, and also shares some features with Python, Lisp and CLU. It was originally designed as an interpreted language, though in its JRuby implementation it may be compiled.
| Contents |
History
The language was created by Yukihiro "Matz" Matsumoto, who started working on Ruby on February 24, 1993 and released it to the public in 1995. He chose the name to reflect the language's Perl heritage. According to the author, he designed Ruby to follow the principle of least surprise (PoLS), meaning that the language should be free from the traps and inconsistencies that plague other languages. As of February 2004, the stable version is 1.8.1.
Philosophy
Ruby is object-oriented: every bit of data is an object, including types that are designated "primitive" in other languages such as integers. Every function is a method. Named values (variables) designate references to objects, not the objects themselves. Ruby supports inheritance with dynamic dispatch, mixins, and singleton methods (belonging to a class rather than an instance). Though Ruby does not support multiple inheritance, classes can import modules as mixins. Procedural syntax is possible, but anything done in Ruby procedurally (ie. outside of the scope of a particular object) is actually done to the Object class. Since this class is parent to every other class, the changes become visible to all classes and objects.
Ruby has also been described as a multi-paradigm programming language: it allows you to program procedurally (defining a function/variable outside a class makes it part of the root 'self' Object), object-orientated (everything is an object) or functionally (anonymous functions, closures, continuations, all expressions return a value, when no return statement is present, functions return the last value evaluated). It has rich support for introspection, reflection and metaprogramming.
According to the Ruby FAQ, "If you like Perl, you will like Ruby and be right at home with its syntax. If you like Smalltalk, you will like Ruby and be right at home with its semantics. If you like Python, you may or may not be put off by the huge difference in design philosophy between Python and Ruby/Perl."
Implementations
Ruby has two main implementations, the official Ruby interpreter, which is the most widely used and JRuby, a Java-based implementation. The standard interpreter has been ported to many platforms, including Unix, Microsoft Windows, DOS, Mac OS X, OS/2, Amiga, and many more. The Ruby distribution also includes IRB, an interactive command-line interpreter which can be used to quickly test out code.
Licensing terms
Ruby is distributed disjointly under the free and open source licences GPL and Ruby License [1].
Features
- object-orientation
- exception handling
- iterators and closures (based on passable blocks of code)
- native, Perl-like regular expression at the language level
- operator overloading
- automatic garbage collection
- multithreading on all platforms
- DLL loading on Microsoft Windows
- support for introspection, reflection and metaprogramming
- large standard library
Ruby currently lacks support for Unicode, though it has partial support for UTF-8.
Pitfalls (possible surprises)
While Ruby design was guided by the principle of least surprise, there are nevertheless features that may surpise programmers who are used to languages such as C or Perl:
- Global variable names may not begin with a capital letter - otherwise the variable is treated as a constant.
- 0 is true: In C, the expression 0 ? 1 : 0 is evaluated as 0. In Ruby, however, it yields 1. Rationale: In Ruby, certain expressions (e.g. regular expression tests) return either a numeric value or "nil". When such a return value is evaluated in a boolean context, only "nil" is evaluated as "false"; every numeric value, including 0, is considered "true". In other words, there is no automatic conversion from numeric to boolean data type.
- Class methods that take no argument may be called without parentheses: my_array.size is sufficient, no need to write my_array.size().
Examples
Here are some basic examples of Ruby code:
# everything, including literals, 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"
Collections
Constructing and 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:
h = {'water' => 'wet', 'fire' => 'hot'}
puts h['fire']
h.each_pair do |key, value|
puts "#{key} is #{value}"
end
# water is wet
# fire is hot
h.delete_if { |k,v| k == 'water' } # deletes 'water' => 'wet'
Blocks and iterators
Two different ways of making blocks:
{ puts "Hello, World!" }
do puts "Hello, World" end
Passing a block as a parameter (closure concept):
def func name
yield name
end
# call the function with a name and a block
func("John") do |name|
puts "Hello, #{name}"
end
# prints "Hello, John"
Iterating through an array using closures:
a = [1, 'hi', 3.14]
a.each { |item| puts item } # prints each element
3.upto(6) { |num| puts num } # prints the numbers 3 to 6
Iterators are part of almost every built-in class:
IO.readlines('file.txt') do |line|
# .. process each line here
end
Using map to calculate squares from 1 to 10:
(1..10).map { |x| x*x }
=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Classes
The following code defines a class named Person in which the initialize method is a constructor (it is called when creating a new object), and two methods: one overloading the <=> comparison operator (so Array#sort can sort by age) and the to_s method (so Kernel#puts knows how to format the output). The attr_reader is an example of metaprogramming in ruby, it defines read/write methods for instance variables (in this case only read methods). The code then creates an array called group with three elements and prints it sorted by age in reverse order.
class Person
def initialize(name, age)
@name, @age = name, age
end
def <=>(person)
@age <=> person.age
end
def to_s
"#{@name} (#{@age})"
end
attr_reader :name, :age
end
group = [ Person.new("John", 20),
Person.new("Markus", 63),
Person.new("Ash", 16)
]
puts group.sort.reverse
This code generates the following output:
Markus (63) John (20) Ash (16)
More Ruby code is available in the form of sample algorithm implementations in the following articles:
External links
- Ruby home page
- Ruby Garden
- Programming Ruby—Full text of the book by David Thomas & Andrew Hunt, ISBN 0-201-71089-7
- Why's Poignant Guide to Ruby
- Ruby FAQ, or the old version
- Ruby Application Archive
- JRuby
- The Ruby Documentation project
- Ruby Forum
- RubyForge
| Major programming languages (more) | ||
|
Ada | ALGOL | APL | AWK | BASIC | C | C++ | C# | COBOL | Delphi | Eiffel | Fortran | Haskell | IDL | Java | JavaScript | Lisp | LOGO | ML | Objective-C | Pascal | Perl | PHP | PL/I | Prolog | Python | Ruby | SAS | Scheme | sh | Simula | Smalltalk | SQL | Visual Basic | ||
de:Ruby es:Lenguaje de programación Ruby eo:Ruby Komputillingvo fr:Ruby it:Ruby nl:Programmeertaal Ruby ja:Ruby pl:Ruby (język programowania) ru:Ruby sv:Ruby zh:Ruby编程语言 he:Ruby