Dynamic programming language is a term used broadly in computer science to describe a class of high level programming langua... , reflectiveReflection (computer science)
In computer science, reflection is the process by which a computer program of the appropriate type can be modified in the pr... , general purpose object-oriented programming languageObject-oriented programming language
An object-oriented programming language is one that allows or encourages, to some degree, object-oriented programming metho... that combines syntax inspired by PerlPerl
Perl, also Practical Extraction and Report Language is a dynamic procedural programming language designed by Larry Wa... with SmalltalkSmalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language.... -like features. Ruby originated in JapanJapan
is an island country in East Asia. Located in the Pacific Ocean, it lies to the east of China, Korea, and Russia, stretching from... during the mid-1990s and was initially developed and designed by Yukihiro "Matz" MatsumotoYukihiro Matsumoto
Yukihiro Matsumoto, a.k.a. Matz is a Japanese computer scientist and free software programmer best known as the c... .
A programming paradigm is a paradigmatic style of programming.... s, including functionalFunctional programming
Functional programming is a programming paradigm that conceives computation as the evaluation of mathematical functions and ... , object orientedObject-oriented programming
In computer science, object-oriented programming is a computer programming paradigm.... , imperativeImperative programming
In computer science, imperative programming, as contrasted with declarative programming, is a programming paradigm that desc... and reflectionReflection (computer science)
In computer science, reflection is the process by which a computer program of the appropriate type can be modified in the pr... . It also has a dynamic type system and automatic memory managementMemory management
Memory management is the act of managing computer memory.... ; it is therefore similar in varying respects to PythonPython (programming language)
Python is a programming language created by Guido van Rossum in 1990.... , PerlPerl
Perl, also Practical Extraction and Report Language is a dynamic procedural programming language designed by Larry Wa... , Lisp, Dylan, and CLU.
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby programming language.... , written in CC (programming language)
The C programming language is a general-purpose, procedural, imperative computer programming language developed in the earl... , Ruby is a single-pass interpreted languageFacts About Interpreted language
In computer programming, an interpreted language is a programming language whose programs may be executed from source form, ... . There is currently no specification of the Ruby language, so the original implementation is considered to be the de facto reference. As of 2008, there are a number of complete or upcoming alternative implementations of the Ruby language, including YARVYARV
YARV is the new bytecode interpreter that is being developed for the Ruby programming language.... , JRubyJRuby
JRuby is a pure Java implementation of the Ruby interpreter, being developed by the JRuby team.... , RubiniusRubinius
IronRuby is an upcoming implementation of the Ruby programming language targeting Microsoft .NET framework.... , and MacRuby, each of which takes a different approach, with JRuby and IronRuby providing just-in-time compilationJust-in-time compilation
In computing, just-in-time compilation, also known as dynamic translation, is a technique for improving the performanc... functionality.
Yukihiro Matsumoto, a.k.a. Matz is a Japanese computer scientist and free software programmer best known as the c... , who started working on Ruby on February 24, 1993, and released it to the public in 1995. "Ruby" was named as a gemstone because of a joke within Matsumoto's circle of friends alluding to the name of the PerlPerl
Perl, also Practical Extraction and Report Language is a dynamic procedural programming language designed by Larry Wa... programming language.
As of June 2008, the latest stable version of the reference implementation is 1.8.7. Apart from the reference, several other virtual machineVirtual machine
In computer science, a virtual machine is software that creates a virtualized environment between the computer platform so t... s are being developed for Ruby. These include JRubyJRuby
JRuby is a pure Java implementation of the Ruby interpreter, being developed by the JRuby team.... , a port of Ruby to the JavaJava (programming language)
Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1... platform, IronRubyIronRuby
IronRuby is an upcoming implementation of the Ruby programming language targeting Microsoft .NET framework.... , an implementation for the .NET Framework.NET Framework
The Microsoft .NET Framework is a software component which can be added to the Microsoft Windows operating system.... produced by MicrosoftMicrosoft
company_name = Microsoft Corporation| company_logo = ... , and RubiniusFacts About Rubinius
name = Rubinius| logo =... , an interpreterInterpreter (computing)
An interpreter is a computer program that executes other programs.... modeled after self-hostingSelf-hosting
Self-hosting refers to the use of a computer program as part of the toolchain or operating system that produces new versions... SmalltalkSmalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language.... virtual machines.
Yukihiro Matsumoto, a.k.a. Matz is a Japanese computer scientist and free software programmer best known as the c... , has said that Ruby is designed for programmer productivity and fun, following the principles of good user interfaceUser interface
The user interface is the aggregate of means by which people interact with a particular machine, device, computer program o... design. He stresses that systems design needs to emphasize human, rather than computer, needs :
Ruby is said to follow the principle of least surprise (POLS), meaning that the language should behave in such a way as to minimize confusion for experienced users. Matsumoto has said his primary design goal was to make a language which he himself enjoyed using, by minimizing programmer work and possible confusion. He has said he had not applied the principle of least surprise to the design of Ruby, but nevertheless the phrase has come to be closely associated with the Ruby programming language. The phrase has itself been a source of surprise, as novice users may take it to mean that Ruby's behaviors try to closely match behaviors familiar from other languages. In a May 2005 discussion on the comp.lang.ruby newsgroup, Matsumoto attempted to distance Ruby from POLS, explaining that because any design choice will be surprising to someone, he uses a personal standard in evaluating surprise. If that personal standard remains consistent there will be few surprises for those familiar with the standard.
Matsumoto defined it this way in an interview:
Type system
Ruby never inherently checks the type of any expression entered in code; rather, if a method deems a type error to have occurred, then it raises a TypeError.
To demonstrate this point, the code 1 + "a" results in a TypeError (String can't be coerced into Fixnum), but this is not an inherent or unchangeable property; we could, should we desire, redefine the method Fixnum#+ to not throw a TypeError, but do something else. Ruby never checks the type with intent; only the program code does. Another error of type occurs when a method is called that doesn't exist (the object does not have the expected type, be the properties of that type inherited from class or added at runtime).
In computer science, type safety is a property attributed to some, but not all, programming languages.... " has no universally agreed upon definition. Whether or not Ruby is "type safe" depends on which definition is applied.
One definition of "type-safe language" requires that: "No operation will be applied to a variable of a wrong type." In this respect, Ruby is probably type safe. Although Ruby's semantics make such an assertion very difficult to prove theoretically, it could be assumed so long as no contradictory code example can be found.
Another definition of a "type-safe program" requires that: "The program will not have type errors when it runs." In this respect, Ruby is obviously not type safe, since, by design, a Ruby program can raise type errors (via the TypeError exception class) during execution.
Is Ruby strongly typed?
Again, there is no universally agreed upon definition of "strongly typed". C2.com Wiki lists at least from different sources. According to some of these definitions, Ruby is strongly typed, while according to others it is weakly typed:
"A language is strongly typed if type annotations are associated with variable names, rather than with values. If types are attached to values, it is weakly typed." ⇒ Ruby is weakly typed. (Some object to this definition, calling it dynamic typing instead and citing Common LispCommon Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, standardised by ANSI X3.226-1994.... as strongly, dynamically typed.)
"A language is strongly typed if it contains compile-time checks for type constraint violations. If checking is deferred to run time, it is weakly typed." ⇒ Ruby is weakly typed. (Common Lisp again falls into this category.)
"A language is strongly typed if there are compile-time or run-time checks for type constraint violations. If no checking is done, it is weakly typed." ⇒ Ruby is strongly typed.
"A language is strongly typed if conversions between different types are forbidden. If such conversions are allowed, it is weakly typed." ⇒ Ruby is weakly typed. (Every practical programming language would count as weakly typed under this very restrictive definition, for example integers could not be converted to floating point values.)
"A language is strongly typed if conversions between different types must be indicated explicitly. If implicit conversions are performed, it is weakly typed." ⇒ Ruby is weakly typed. (Example: in the expression 2+3.5, the Fixnum expression 2 is implicitly converted to Float.)
"A language is strongly typed if there is no language-level way to disable or evade the type system. If there are casts or other type-evasive mechanisms, it is weakly typed." ⇒ Ruby is assumed to be strongly typed, but very difficult to prove mathematically.
"A language is strongly typed if it has a complex, fine-grained type system with compound types. If it has only a few types, or only scalar types, it is weakly typed." ⇒ Ruby is strongly typed. (Since compound types are vital to most applications, this definition would make nearly all modern, practical languages strongly typed.)
"A language is strongly typed if the type of its variables is fixed and does not vary over the lifetime of the variable. If the type of the datum stored in a variable can change, the language is weakly typed." ⇒ Ruby is weakly typed. (Example: x = 1; x = "s". Type of x changes from Fixnum to String.)
Types vs. classes
In Ruby, the questions of being type-safe, or strongly typed, are less important than as in other programming languages, due to the fact that there is no solid definition of a "type". This arises from the fact that any class can be extended at runtime (even base, built-in classes), and instance objects can also be individually extended. This means that, although an object may be of any given class, it may be extended, thus rendering a different type. The definitions of type-safe and 'strongly typed' run contrary to the base philosophy of Ruby, which is that explicit class checking should not be performed (hence lacking variable types in parameter lists); instead, any object which responds to the methods or behaviors a function requires is considered to be sufficient.
Features
object-oriented
five levels of variable scope: globalGlobal variable
In computer programming, a global variable is a variable that does not belong to any subroutine or class and can be accessed... , classClass variable
In object-oriented programming with classes, a class variable is a variable defined in a class of which a single copy exists... , instanceInstance variable
In object-oriented programming with classes, an instance variable is a variable defined in a class, for which each object in... , localLocal variable
In computer science, a local variable is a variable that is given local scope.... , and block
In computer science, an iterator is an object which allows a programmer to traverse through all the elements of a collection... s and closuresClosure (computer science)
In programming languages, a closure is a function that refers to free variables in its lexical context.... (based on passing blocks of code)
Perl, also Practical Extraction and Report Language is a dynamic procedural programming language designed by Larry Wa... -like regular expressionRegular expression
A regular expression is a string that describes or matches a set of strings, according to certain syntax rules.... s at the language level
Dynamic-link library, also known as dynamic link library, is Microsoft's implementation of the shared library concept ... /shared libraryLibrary (computer science)
In computer science, a library is a collection of subprograms used to develop software.... dynamic loading on most platforms
In computer science, reflection is the process by which a computer program of the appropriate type can be modified in the pr... and metaprogrammingMetaprogramming
Metaprogramming is the writing of programs that write or manipulate other programs as their data or that do part of the work...
In computing, a continuation is a representation of the execution state of a program at a certain point.... s and generatorsGenerator (computer science)
In computer science, a generator is a special routine that can be used to control the iteration behaviour of a loop.... (examples in RubyGarden: and )
Ruby currently lacks full support for UnicodeUnicode
Unicode is an industry standard designed to allow text and symbols from all of the writing systems of the world to be consis... , though it has partial support for UTF-8UTF-8
UTF-8 is a variable-length character encoding for Unicode created by Ken Thompson and Rob Pike.... .
Interaction
The Ruby official distribution also includes "irb", an interactive command-line interpreter which can be used to test code quickly. The following code fragment represents a sample session using irb:
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 sigilSigil (computer programming)
In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype.... . 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 braces (i.e., pair of ). For practical purposes there is no distinction between expressionsExpression (programming)
An expression in a programming language is a combination of values, variables, operators, and functions that are interpreted... and statementsStatement (programming)
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming langua... statement [...] can not be part of expression unless grouped within parentheses. http://ruby-talk.com/2460 . Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Unlike Python, indentation is not significant.
One of the differences of Ruby compared to Python and Perl is that Ruby keeps all of its instance variables completely private to the class and only exposes them through accessor methods (attr_writer, attr_reader, etc). Unlike the "getter" and "setter" methods of other languages like C++ or Java, accessor methods in Ruby can be written with a single line of code. As invocation of these methods does not require the use of parentheses, it is trivial to change an instance variable into a full function, without modifying a single line of code or having to do any refactoring achieving similar functionality to C# and VB.NET property members. Python's property descriptors are similar, but come with a tradeoff in the development process. If one begins in Python by using a publicly exposed instance variable and later changes the implementation to use a private instance variable exposed through a property descriptor, code internal to the class may need to be adjusted to use the private variable rather than the public property. Ruby removes this design decision by forcing all instance variables to be private, but also provides a simple way to declare set and get methods. This is in keeping with the idea that in Ruby, one never directly accesses the internal members of a class from outside of it. Rather one passes a message to the class and receives a response.
See the examples section for samples of code demonstrating Ruby syntax.
"Gotchas"
Language features
Ruby code runs slower than many compiled languages (as is typical for interpreted languages) and other major scripting languages such as PythonPython (programming language)
Python is a programming language created by Guido van Rossum in 1990.... and PerlPerl
Perl, also Practical Extraction and Report Language is a dynamic procedural programming language designed by Larry Wa... . However, in future releases (current revision: 1.9), Ruby will be bytecode compiledBytecode
Bytecode is an intermediate code more abstract than machine code.... to be executed on YARVYARV
YARV is the new bytecode interpreter that is being developed for the Ruby programming language.... (Yet Another Ruby VM). Ruby's current memory footprintMemory footprint
Memory footprint refers to the amount of main memory that a program uses or references while running.... for the same operations is higher than Perl's and Python's.
Omission of parentheses around method arguments may lead to unexpected results if the methods take multiple parameters. The Ruby developers have stated that omission of parentheses on multi-parameter methods may be disallowed in future Ruby versions; the current (Nov 2007) Ruby interpreter throws a warning which encourages the writer not to omit , to avoid ambiguous meaning of code. Not using is still common practice, and can be especially nice to use Ruby as a human readable domain-specific programming languageDomain-specific programming language
A domain-specific programming language is a programming language designed to be useful for a specific set of tasks.... itself, along with the method called method_missing.
A list of "gotchas" may be found in Hal Fulton's book The Ruby Way, 2nd ed (ISBN 0-672-32884-4), Section 1.5. A similar list in the 1st edition pertained to an older version of Ruby (version 1.6), some problems of which have been fixed in the meantime. retry, for example, now works with while, until, and for, as well as iterators.
Examples
The following examples can be run in a Ruby shell such as Interactive Ruby ShellInteractive Ruby Shell Summary
Interactive Ruby Shell is a shell for programming in the object-oriented scripting language Ruby.... or saved in a file and run from the command line by typing ruby .
Classic Hello world example:
puts "Hello World!"
Some basic Ruby code:
Everything, including a literal, is an object, so this works:
-199.abs# 199 "ruby is cool".length # 12 "Rick Astley".index("c")# 2 "Nice Day Isn't It?".downcase.split(//).sort.uniq.join # " '?acdeinsty"
Conversions:
puts 'What\'s your favorite number?' number = gets.chomp outputnumber = number.to_i + 1 puts outputnumber.to_s + ' is a bigger and better favorite number.'
Strings
There are a variety of methods of defining strings in Ruby
The below conventions are equivalent for double quoted strings: a = "\nThis is a double quoted string\n" a = %Q a = <This is a multi-line double quoted string BLOCK a = %/\nThis is a double quoted string\n/
The below conventions are equivalent for single quoted strings: a = 'This is a single quoted string' a = %q
The following code defines a class named Person. In addition to 'initialize', the usual constructor to create new objects, it has two methods: one to override the <=> comparison operator (so Array#sort can sort by age) and the other to override the to_s method (so Kernel#puts can format its output). Here, "attr_reader" is an example of metaprogramming in Ruby: "attr_accessor" defines getter and setter methods of instance variables, "attr_reader" only getter methods. Also, the last evaluated statement in a method is its return value, allowing the omission of an explicit 'return'.
class Person def initialize(name, age) @name, @age = name, age end def <=>(person) # Comparison operator for sorting @age <=> person.age end def to_s "#@name (#@age)" end attr_reader :name, :age end
group = [ Person.new("Bob", 33), Person.new("Chris", 16), Person.new("Ash", 23) ]
puts group.sort.reverse
The above prints three names in reverse age order: Bob (33) Ash (23) Chris (16)
Exceptions
An exception is raised with a raise call: raise
An optional message can be added to the exception: raise "This is a message"
You can also specify which type of exception you want to raise: raise ArgumentError, "Illegal arguments!"
Alternatively, you can pass an exception instance to the raise method: raise ArgumentError.new( "Illegal arguments!" )
This last construct is useful when you need to raise a custom exception class featuring a constructor which takes more than one argument: class ParseError < Exception def initialize input, line, pos super "Could not parse '#' at line #, position #" end end
raise ParseError.new( "Foo", 3, 9 )
Exceptions are handled by the rescue clause. Such a clause can catch exceptions which inherit from StandardError:
begin
Do something
rescue
Handle exception
end
It is a common mistake to attempt to catch all exceptions with a simple rescue clause. To catch all exceptions one must write:
begin
Do something
rescue Exception # don't write just rescue -- this only catches StandardError, a subclass of Exception
Handle exception
end
Or catch particular exceptions:
begin
...
rescue RuntimeError
handling
end
It is also possible to specify that the exception object be made available to the handler clause:
begin
...
rescue RuntimeError => e
handling, possibly involving e, such as "print e.to_s"
end
Alternatively, the most recent exception is stored in the magic global $!.
You can also catch several exceptions: begin
...
rescue RuntimeError, TimeoutError => e
handling, possibly involving e
end
Or catch an array of exceptions: array_of_exceptions = [RuntimeError, TimeoutError] begin
...
rescue *array_of_exceptions => e
handling, possibly involving e
end
More examples
More sample Ruby code is available as algorithms in the following articles:
The Trabb Pardo-Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of ...
Implementations
Ruby has two main implementations: The official Ruby interpreter often referred to as the Matz's Ruby InterpreterRuby MRI
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby programming language.... or MRI, which is the most widely used, and JRubyJRuby
JRuby is a pure Java implementation of the Ruby interpreter, being developed by the JRuby team.... , a JavaJava (programming language)
Java is an object-oriented programming language developed by James Gosling and colleagues at Sun Microsystems in the early 1... -based implementation.
There are other less known implementations such as IronRubyIronRuby
IronRuby is an upcoming implementation of the Ruby programming language targeting Microsoft .NET framework.... , RubiniusRubinius
YARV is the new bytecode interpreter that is being developed for the Ruby programming language.... . YARV is Ruby 1.9's official new virtual machine and is no longer a separate project.
The maturity of Ruby implementations tend to be measured by their ability to run RailsRuby on Rails
Ruby on Rails, often called RoR, or just Rails, is an open source web application framework written in Ruby that... (because this is a complex framework to implement, and it uses a lot of Ruby-specific features). The point when a particular implementation achieves this goal is called The Rails singularity. As of May 2008, only the reference implementation (MRI)Ruby MRI
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby programming language.... and JRubyJRuby
JRuby is a pure Java implementation of the Ruby interpreter, being developed by the JRuby team.... are able to run Rails unmodified in a production environment. IronRubyIronRuby
IronRuby is an upcoming implementation of the Ruby programming language targeting Microsoft .NET framework.... and RubiniusRubinius
name = Rubinius| logo =... start to be able to run Rails test cases, but they still are far from production ready for this task.
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby programming language.... , Ruby is available on a lot of operating systemOperating system
An operating system is a software program that manages the hardware and software resources of a computer.... s such as LinuxLinux
Linux is a Unix-like computer operating system.... , Mac OS XMac OS X
Mac OS X is a line of proprietary, graphical operating systems developed, marketed, and sold by Apple Computer, the latest ... , Microsoft WindowsMicrosoft Windows
Microsoft Windows is a family of operating systems by Microsoft.... , Windows CEWindows CE
Windows CE is a variation of Microsoft's Windows operating system for minimalistic computers and embedded systems.... and most flavors of UnixUnix
Unix or UNIX is a computer operating system originally developed in the 1960s and 1970s by a group of AT&T Bell Labs e... .
Criticism
A number of the design choices made for Ruby have well-known disadvantages:
In computer programming, BASIC refers to a family of high-level programming languages.... , because variables are not required to be declaredDeclaration (computer science)
In computer science, a declaration specifies a variable's dimensions, identifier, type, and other aspects.... before use, typing errors can introduce new variables and cause unexpected behavior.
Dynamic typing can cause type errors to be found later in the development process, making them more expensive to fix, and add runtime overhead compared to static typing.
The runtime extensible environment enabled by metaprogramming can make programs more difficult to reason about statically and inhibit some types of optimizations.
The Ruby threading model uses green threadsGreen threads
In computer programming, Green threads are threads that are scheduled by a Virtual Machine instead of natively by the under... , and its model has some inherent limitations which render it difficult to use or unsafe in some scenarios.
Ruby 1.8 does not yet have native support for UnicodeUnicode
Unicode is an industry standard designed to allow text and symbols from all of the writing systems of the world to be consis... or multibyte strings, although 1.9 added multiple improvements in this area.
Ruby suffers from backward compatibility problems.
Ruby 2.0 aims to address all of the aforementioned problems:
Native threads will be used instead of green threads.
Full support for Unicode strings.
Some problems which may not be solved in version 2.0 include:
Ruby still lacks a specification, the current C implementation being the de facto reference specification.
Ruby Application Archive is a repository of applications for Ruby programming language development.... (RAA), as well as RubyForgeRubyForge
RubyForge is a collaborative software development management system dedicated to projects related Ruby programming language.... , serve as repositories for a wide range of Ruby applications and libraries, containing more than seven thousand items. Although the number of applications available does not match the volume of material available in the PerlPerl
Perl, also Practical Extraction and Report Language is a dynamic procedural programming language designed by Larry Wa... or PythonFacts About Python (programming language)
Python is a programming language created by Guido van Rossum in 1990.... community, there are a wide range of tools and utilities which serve to foster further development in the language.
RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby progra... has become the standard package manager for Ruby libraries. It is very similar in purpose to Perl's CPANCPAN
CPAN is an acronym standing for Comprehensive Perl Archive Network.... , although its usage is more like apt-get.