Ruby (programming language)
Encyclopedia
Ruby is a dynamic
, reflective
, general-purpose object-oriented programming language
that combines syntax inspired by Perl
with Smalltalk
-like features. Ruby originated in Japan
during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto
. It was influenced primarily by Perl
, Smalltalk
, Eiffel
, and Lisp.
Ruby supports multiple programming paradigm
s, including functional
, object oriented
, imperative
and reflective. It also has a dynamic type system and automatic memory management
; it is therefore similar in varying respects to Smalltalk
, Python
, Perl
, Lisp, Dylan, Pike, and CLU.
The standard 1.8.7 implementation
is written in C
, as a single-pass interpreted language
. The specifications of Ruby language are currently being developed by the Open Standards Promotion Center of the Information-Technology Promotion Agency (a Japanese government agency) for submission to the Japanese Industrial Standards Committee and then further on to the International Organization for Standardization. So far they have come up with a final draft of specifications which is yet to be accepted as an Industrial Standard. , there are a number of complete or upcoming alternative implementations of the Ruby language, including YARV
, JRuby
, Rubinius
, IronRuby
, MacRuby
, and HotRuby
. Each takes a different approach, with IronRuby, JRuby and MacRuby providing just-in-time compilation
and MacRuby also providing ahead-of-time compilation. The official 1.9 branch uses YARV
, as will 2.0 (development), and will eventually supersede the slower Ruby MRI
.
who wished to create a new language that balanced functional programming
with imperative programming
. Matsumoto has stated, "I wanted a scripting language
that was more powerful than Perl
, and more object-oriented than Python
. That's why I decided to design my own language".
At a Google Tech Talk in 2008 Matsumoto further stated, "I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy.
That is the primary purpose of Ruby language."
s on December 21, 1995. Subsequently three more versions of Ruby were released in two days. The release coincided with the launch of the Japanese language ruby-list mailing list which was the first mailing list for the new language.
Already present at this stage of development were many of the features familiar in later releases of Ruby, including object-oriented design, classes
with inheritance, mixin
s, iterator
s, closure
s, exception handling
, and garbage collection
.
Following the release of Ruby 1.3 in 1999 the first English language mailing list ruby-talk began, which signalled a growing interest in the language outside of Japan. In September 2000, the first English language book Programming Ruby
was printed, which was later freely released to the public further widening the adoption of Ruby amongst English speakers.
, a popular web application framework
written in Ruby. Rails is frequently credited with making Ruby "famous".
Ruby 1.9 introduces many significant changes over the 1.8 series. Some examples are:
design. He stresses that systems design needs to emphasize human, rather than computer, needs:
Ruby is said to follow the principle of least astonishment
(POLA), 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 that 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 POLA, 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:
s, booleans, and "nil"). Variables always hold references to objects. Every function is a method and methods are always called on an object. Methods defined at the top level scope become members of the Object class. Since this class is an ancestor of every other class, such methods can be called on any object. They are also visible in all scopes, effectively serving as "global" procedures. Ruby supports inheritance
with dynamic dispatch
, mixin
s and singleton methods (belonging to, and defined for, a single instance
rather than being defined on the class). Though Ruby does not support multiple inheritance
, classes can import modules as mixins.
Ruby has been described as a multi-paradigm programming language
: it allows procedural programming (defining functions/variables outside classes makes them part of the root, 'self' Object), with object orientation (everything is an object) or functional programming
(it has anonymous function
s, closures
, and continuation
s; statements all have values, and functions return the last evaluation). It has support for introspection, reflection
and metaprogramming
, as well as support for interpreter-based thread
s. Ruby features dynamic typing
, and supports parametric polymorphism
.
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."
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 braces (i.e., pair of { and }). For practical purposes there is no distinction between expressions
and statements
. 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 (
or Java
, accessor methods in Ruby are created with a single line of code via metaprogramming
. 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’s design forces all instance variables to be private, but also provides a simple way to declare
See the examples section for samples of code demonstrating Ruby syntax.
or Perl
:
Some features which differ notably from other languages:
A list of so-called 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.
Interaction
The Ruby official distribution also includes "
Dynamic programming language
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all...
, reflective
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....
, general-purpose object-oriented programming language
Object-oriented programming language
This is a list of object-oriented programming programming languages.-Languages with object-oriented features:*ABAP*Ada 95*AmigaE*BETA*Blue*Boo*C++*C#*COBOL*Cobra*ColdFusion*Common Lisp*COOL*CorbaScript*Clarion*CLU*Curl*D*Dylan*E*Eiffel...
that combines syntax inspired by Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
with Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
-like features. Ruby originated in Japan
Japan
Japan is an island nation in East Asia. Located in the Pacific Ocean, it lies to the east of the Sea of Japan, China, North Korea, South Korea and Russia, stretching from the Sea of Okhotsk in the north to the East China Sea and Taiwan in the south...
during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto
Yukihiro Matsumoto
is a Japanese computer scientist and software programmer best known as the chief designer of the Ruby programming language and its reference implementation, Matz's Ruby Interpreter ....
. It was influenced primarily by Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
, Eiffel
Eiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...
, and Lisp.
Ruby supports multiple programming paradigm
Programming paradigm
A programming paradigm is a fundamental style of computer programming. Paradigms differ in the concepts and abstractions used to represent the elements of a program and the steps that compose a computation A programming paradigm is a fundamental style of computer programming. (Compare with a...
s, including functional
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
, object oriented
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
, imperative
Imperative programming
In computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state...
and reflective. It also has a dynamic type system and automatic memory management
Memory management
Memory management is the act of managing computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed. This is critical to the computer system.Several...
; it is therefore similar in varying respects to Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, Lisp, Dylan, Pike, and CLU.
The standard 1.8.7 implementation
Ruby MRI
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby programming language. As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference. The RubySpec project has created a large test suite that captures...
is written in C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
, as a single-pass interpreted language
Interpreted language
Interpreted language is a programming language in which programs are 'indirectly' executed by an interpreter program. This can be contrasted with a compiled language which is converted into machine code and then 'directly' executed by the host CPU...
. The specifications of Ruby language are currently being developed by the Open Standards Promotion Center of the Information-Technology Promotion Agency (a Japanese government agency) for submission to the Japanese Industrial Standards Committee and then further on to the International Organization for Standardization. So far they have come up with a final draft of specifications which is yet to be accepted as an Industrial Standard. , there are a number of complete or upcoming alternative implementations of the Ruby language, including YARV
YARV
YARV is a bytecode interpreter that was developed for the Ruby programming language by Koichi Sasada. The goal of the project was to greatly reduce the execution time of Ruby programs....
, JRuby
JRuby
JRuby is a Java implementation of the Ruby programming language, being developed by the JRuby team. It is free software released under a three-way CPL/GPL/LGPL license...
, Rubinius
Rubinius
Rubinius is an alternative Ruby programming language implementation created by Evan Phoenix. Based loosely on the Smalltalk-80 Blue Book design, Rubinius seeks to"provide a rich, high-performance environment for running Ruby code."-Goals:...
, IronRuby
IronRuby
IronRuby is an implementation of the Ruby programming language targeting Microsoft .NET framework. It is implemented on top of the Dynamic Language Runtime , a library running on top of the Common Language Infrastructure that provides dynamic typing and dynamic method dispatch, among other things,...
, MacRuby
MacRuby
MacRuby is an implementation of the Ruby language that runs on the Objective-C runtime and CoreFoundation framework under development by Apple Inc. which "is supposed to replace RubyCocoa". It is based on Ruby 1.9 and uses the high performance Low Level Virtual Machine compiler infrastructure...
, and HotRuby
HotRuby
HotRuby is a Javascript and ActionScript implementation of the Ruby programming language. HotRuby runs Ruby source code on a web browser and Flash...
. Each takes a different approach, with IronRuby, JRuby and MacRuby providing just-in-time compilation
Just-in-time compilation
In computing, just-in-time compilation , also known as dynamic translation, is a method to improve the runtime performance of computer programs. Historically, computer programs had two modes of runtime operation, either interpreted or static compilation...
and MacRuby also providing ahead-of-time compilation. The official 1.9 branch uses YARV
YARV
YARV is a bytecode interpreter that was developed for the Ruby programming language by Koichi Sasada. The goal of the project was to greatly reduce the execution time of Ruby programs....
, as will 2.0 (development), and will eventually supersede the slower Ruby MRI
Ruby MRI
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby programming language. As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference. The RubySpec project has created a large test suite that captures...
.
History
Ruby was conceived on February 24, 1993 by Yukihiro MatsumotoYukihiro Matsumoto
is a Japanese computer scientist and software programmer best known as the chief designer of the Ruby programming language and its reference implementation, Matz's Ruby Interpreter ....
who wished to create a new language that balanced functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
with imperative programming
Imperative programming
In computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state...
. Matsumoto has stated, "I wanted a scripting language
Scripting language
A scripting language, script language, or extension language is a programming language that allows control of one or more applications. "Scripts" are distinct from the core code of the application, as they are usually written in a different language and are often created or at least modified by the...
that was more powerful than Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, and more object-oriented than Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
. That's why I decided to design my own language".
At a Google Tech Talk in 2008 Matsumoto further stated, "I hope to see Ruby help every programmer in the world to be productive, and to enjoy programming, and to be happy.
That is the primary purpose of Ruby language."
Etymology of the name "Ruby"
The name "Ruby" was decided on during an online chat session between Matsumoto and Keiju Ishitsuka on February 24, 1993, before any code had been written for the language. Initially two names were proposed: "Coral" and "Ruby", with the latter being chosen by Matsumoto in a later email to Ishitsuka. Matsumoto has later stated that a factor in choosing the name "Ruby" was because it was the birthstone of one of his colleagues.First publication
The first public release of Ruby 0.95 was announced on Japanese domestic newsgroupNewsgroup
A usenet newsgroup is a repository usually within the Usenet system, for messages posted from many users in different locations. The term may be confusing to some, because it is usually a discussion group. Newsgroups are technically distinct from, but functionally similar to, discussion forums on...
s on December 21, 1995. Subsequently three more versions of Ruby were released in two days. The release coincided with the launch of the Japanese language ruby-list mailing list which was the first mailing list for the new language.
Already present at this stage of development were many of the features familiar in later releases of Ruby, including object-oriented design, classes
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
with inheritance, mixin
Mixin
In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited or just reused by a subclass, while not meant for instantiation , Mixins are synonymous functionally with abstract base classes...
s, iterator
Iterator
In computer programming, an iterator is an object that enables a programmer to traverse a container. Various types of iterators are often provided via a container's interface...
s, closure
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...
s, exception handling
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....
, and garbage collection
Garbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...
.
Ruby 1.0
Ruby reached version 1.0 on December 25, 1996.Following the release of Ruby 1.3 in 1999 the first English language mailing list ruby-talk began, which signalled a growing interest in the language outside of Japan. In September 2000, the first English language book Programming Ruby
Programming Ruby
Programming Ruby is a book about the Ruby programming language by Dave Thomas and Andrew Hunt, authors of The Pragmatic Programmer. In the Ruby community, it is commonly known as "The Pickaxe" because of the pickaxe on the cover...
was printed, which was later freely released to the public further widening the adoption of Ruby amongst English speakers.
Ruby on Rails
Around 2005, interest in the Ruby language surged in tandem with Ruby on RailsRuby on Rails
Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework for the Ruby programming language.-History:...
, a popular web application framework
Web application framework
A web application framework is a software framework that is designed to support the development of dynamic websites, web applications and web services. The framework aims to alleviate the overhead associated with common activities performed in Web development...
written in Ruby. Rails is frequently credited with making Ruby "famous".
Ruby 1.9
The latest stable version of the reference implementation is 1.9.3 and is dual-licensed under the Ruby License and a BSD License.Ruby 1.9 introduces many significant changes over the 1.8 series. Some examples are:
- Block localLocal variableIn computer science, a local variable is a variable that is given local scope. Such a variable is accessible only from the function or block in which it is declared. In programming languages with only two levels of visibility, local variables are contrasted with global variables...
variables (variables that are local to the block in which they are declared) - An additional lambdaAnonymous functionIn programming language theory, an anonymous function is a function defined, and possibly called, without being bound to an identifier. Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions such as Haskell...
syntax (fun = ->(a,b) { puts a + b }
) - Per-string character encodingCharacter encodingA character encoding system consists of a code that pairs each character from a given repertoire with something else, such as a sequence of natural numbers, octets or electrical pulses, in order to facilitate the transmission of data through telecommunication networks or storage of text in...
s are supported - New socket API (IPv6IPv6Internet Protocol version 6 is a version of the Internet Protocol . It is designed to succeed the Internet Protocol version 4...
support)
Philosophy
Matsumoto has said that Ruby is designed for programmer productivity and fun, following the principles of good user interfaceUser interface
The user interface, in the industrial design field of human–machine interaction, is the space where interaction between humans and machines occurs. The goal of interaction between a human and a machine at the user interface is effective operation and control of the machine, and feedback from the...
design. He stresses that systems design needs to emphasize human, rather than computer, needs:
Ruby is said to follow the principle of least astonishment
Principle of least astonishment
The principle of least astonishment applies to user interface design, software design, and ergonomics. It is alternatively referred to as the rule or law of least astonishment, or the rule or principle of least surprise .The POLA states that, when two elements of an interface conflict, or are...
(POLA), 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 that 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 POLA, 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:
Features
- Thoroughly object-oriented with inheritanceInheritance (computer science)In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
, mixinMixinIn object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited or just reused by a subclass, while not meant for instantiation , Mixins are synonymous functionally with abstract base classes...
s and metaclassMetaclassIn object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses...
es - Dynamic typing and Duck typingDuck typingIn computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface...
- Everything is an expressionExpression (programming)An expression in a programming language is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value...
(even statementsStatement (programming)In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...
) and everything is executed imperativelyImperative programmingIn computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state...
(even declarationsDeclaration (computer science)In programming languages, a declaration specifies the identifier, type, and other aspects of language elements such as variables and functions. It is used to announce the existence of the element to the compiler; this is important in many strongly-typed languages that require variables and their...
) - Succinct and flexible syntax that minimizes syntactic noise and serves as a foundation for domain-specific languages
- Dynamic reflectionReflection (computer science)In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....
and alteration of objects to facilitate metaprogrammingMetaprogrammingMetaprogramming is the writing of computer programs that write or manipulate other programs as their data, or that do part of the work at compile time that would otherwise be done at runtime... - Lexical closuresClosure (computer science)In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...
, IteratorIteratorIn computer programming, an iterator is an object that enables a programmer to traverse a container. Various types of iterators are often provided via a container's interface...
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. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values...
, with a unique block syntax - Literal notation for arraysDynamic arrayIn computer science, a dynamic array, growable array, resizable array, dynamic table, or array list is a random access, variable-size list data structure that allows elements to be added or removed...
, hashesAssociative arrayIn computer science, an associative array is an abstract data type composed of a collection of pairs, such that each possible key appears at most once in the collection....
, regular expressions and symbolsSymbol (Lisp)A symbol in computer programming is a primitive datatype whose instances have a unique human-readable form. Symbols can be used as identifiers. In some programming languages, they are called atoms.... - Embedding code in strings (interpolation)
- Default arguments
- Four levels of variable scope (globalGlobal variableIn computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms...
, classClass variableIn object-oriented programming with classes, a class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist.A class variable is the opposite of an instance variable...
, instanceInstance variableIn object-oriented programming with classes, an instance variable is a variable defined in a class , for which each object of the class has a separate copy. They live in memory for the life of the object....
, and localLocal variableIn computer science, a local variable is a variable that is given local scope. Such a variable is accessible only from the function or block in which it is declared. In programming languages with only two levels of visibility, local variables are contrasted with global variables...
) denoted by sigilsSigil (computer programming)In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype or scope. In 1999 Philip Gwyn adopted the term "to mean the funny character at the front of a Perl variable".- Historical context:...
or the lack thereof - Garbage collectionGarbage collection (computer science)In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...
- First-class continuations
- Strict boolean coercion rules (everything is true except
false
andnil
)NilNil is a word commonly used to mean nothing or zero; it is one of several names for the number 0.It may also refer to:- Computer programming :... - Exception handlingException handlingException handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....
- Operator overloadingOperator overloadingIn object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
- Built-in support for rational numbers, complex numbers and arbitrary-precision arithmeticArbitrary-precision arithmeticIn computer science, arbitrary-precision arithmetic indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system. This contrasts with the faster fixed-precision arithmetic found in most ALU hardware, which typically...
- Custom dispatch behavior (through
method_missing
andconst_missing
) - Native threadsThread (computer science)In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...
and cooperative fibersFiber (computer science)In computer science, a fiber is a particularly lightweight thread of execution.Like threads, fibers share address space. However, fibers use co-operative multitasking while threads use pre-emptive multitasking. Threads often depend on the kernel's thread scheduler to preempt a busy thread and... - Initial support for UnicodeUnicodeUnicode is a computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems...
and multiple character encodings (still buggy as of version 1.9) - Native plug-in API in CC (programming language)C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
- Interactive Ruby ShellInteractive Ruby ShellInteractive Ruby Shell is a shell for programming in the object-oriented scripting language Ruby. The program is launched from a command line and allows the execution of Ruby commands with immediate response, experimenting in real-time...
(a REPL) - Centralized package management through RubyGemsRubyGemsRubyGems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries , a tool designed to easily manage the installation of gems, and a server for distributing them. It is analogous to EasyInstall for the Python programming...
- Implemented on all major platforms
- Large standard library
Semantics
Ruby is object-oriented: every value is an object, including classes and instances of types that many other languages designate as primitives (such as integerInteger (computer science)
In computer science, an integer is a datum of integral data type, a data type which represents some finite subset of the mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values....
s, booleans, and "nil"). Variables always hold references to objects. Every function is a method and methods are always called on an object. Methods defined at the top level scope become members of the Object class. Since this class is an ancestor of every other class, such methods can be called on any object. They are also visible in all scopes, effectively serving as "global" procedures. Ruby supports inheritance
Inheritance (object-oriented programming)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
with dynamic dispatch
Dynamic dispatch
In computer science, dynamic dispatch is the process of mapping a message to a specific sequence of code at runtime. This is done to support the cases where the appropriate method can't be determined at compile-time...
, mixin
Mixin
In object-oriented programming languages, a mixin is a class that provides a certain functionality to be inherited or just reused by a subclass, while not meant for instantiation , Mixins are synonymous functionally with abstract base classes...
s and singleton methods (belonging to, and defined for, a single instance
Instance (computer science)
In object-oriented programming an instance is an occurrence or a copy of an object, whether currently executing or not. Instances of a class share the same set of attributes, yet will typically differ in what those attributes contain....
rather than being defined on the class). Though Ruby does not support multiple inheritance
Multiple inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in which a class can inherit behaviors and features from more than one superclass....
, classes can import modules as mixins.
Ruby has been described as a multi-paradigm programming language
Multi-paradigm programming language
Programming languages can be grouped by the number and types of paradigms supported.-Paradigm summaries:A concise reference for the programming paradigms listed in this article....
: it allows procedural programming (defining functions/variables outside classes makes them part of the root, 'self' Object), with object orientation (everything is an object) or functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
(it has anonymous function
Anonymous function
In programming language theory, an anonymous function is a function defined, and possibly called, without being bound to an identifier. Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions such as Haskell...
s, closures
Closure (computer science)
In computer science, a closure is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its typical scope. Such a function is said to be "closed over" its free variables...
, and continuation
Continuation
In computer science and programming, a continuation is an abstract representation of the control state of a computer program. A continuation reifies the program control state, i.e...
s; statements all have values, and functions return the last evaluation). It has support for introspection, reflection
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior at runtime....
and metaprogramming
Metaprogramming
Metaprogramming is the writing of computer programs that write or manipulate other programs as their data, or that do part of the work at compile time that would otherwise be done at runtime...
, as well as support for interpreter-based thread
Thread (computer science)
In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...
s. Ruby features dynamic typing
Type system
A type system associates a type with each computed value. By examining the flow of these values, a type system attempts to ensure or prove that no type errors can occur...
, and supports parametric polymorphism
Parametric polymorphism
In programming languages and type theory, parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety. Using parametric polymorphism, a function or a data type can be written generically so that it can handle values identically without...
.
According to the Ruby FAQ
FAQ
Frequently asked questions are listed questions and answers, all supposed to be commonly asked in some context, and pertaining to a particular topic. "FAQ" is usually pronounced as an initialism rather than an acronym, but an acronym form does exist. Since the acronym FAQ originated in textual...
, "If you like Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, you will like Ruby and be right at home with its syntax. If you like Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
, you will like Ruby and be right at home with its semantics. If you like Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, you may or may not be put off by the huge difference in design philosophy between Python and Ruby/Perl."
Syntax
The syntax of Ruby is broadly similar to PerlPerl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
and Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
. Class and method definitions are signaled by keywords. In contrast to Perl, variables are not obligatorily prefixed with a sigil
Sigil (computer programming)
In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype or scope. In 1999 Philip Gwyn adopted the term "to mean the funny character at the front of a Perl variable".- Historical context:...
. When used, the sigil changes the semantics of scope of the variable. The most striking difference from C and Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
is that keywords are typically used to define logical code blocks, without braces (i.e., pair of { and }). For practical purposes there is no distinction between expressions
Expression (programming)
An expression in a programming language is a combination of explicit values, constants, variables, operators, and functions that are interpreted according to the particular rules of precedence and of association for a particular programming language, which computes and then produces another value...
and statements
Statement (programming)
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...
. 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
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
and Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
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++C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
or Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, accessor methods in Ruby are created with a single line of code via metaprogramming
Metaprogramming
Metaprogramming is the writing of computer programs that write or manipulate other programs as their data, or that do part of the work at compile time that would otherwise be done at runtime...
. 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’s design forces 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.
Deviations from behavior elsewhere
Some features which differ notably from languages such as CC (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
or Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
:
- The language syntax is sensitive to the capitalization of identifiers, in most cases treating capitalized variables as constants.
- The sigilsSigil (computer programming)In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype or scope. In 1999 Philip Gwyn adopted the term "to mean the funny character at the front of a Perl variable".- Historical context:...
$
and@
do not indicate variable data typeData typeIn computer programming, a data type is a classification identifying one of various types of data, such as floating-point, integer, or Boolean, that determines the possible values for that type; the operations that can be done on values of that type; the meaning of the data; and the way values of...
as in Perl, but rather function as scope resolution operatorScope resolution operatorIn computer programming, scope is an enclosing context where values and expressions are associated. The scope resolution operator helps to identify and specify the context to which an identifier refers...
s. - To denote a floating point without a decimal component, one must follow with a zero digit (
99.0
) or an explicit conversion (99.to_f
). It is insufficient to append a dot (99.
) since numbers are susceptible to method syntax. - BooleanBoolean datatypeIn computer science, the Boolean or logical data type is a data type, having two values , intended to represent the truth values of logic and Boolean algebra...
evaluation of non-boolean data is strict:0
,""
and[]
are all evaluated to true. In CC (programming language)C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
, the expression0 ? 1 : 0
evaluates to 0 (i.e. false). In Ruby, however, it yields 1, as all numbers evaluate to true; onlynil
andfalse
evaluate to false. A corollaryCorollaryA corollary is a statement that follows readily from a previous statement.In mathematics a corollary typically follows a theorem. The use of the term corollary, rather than proposition or theorem, is intrinsically subjective...
to this rule is that Ruby methods by convention — for example, regular-expressionRegular expressionIn computing, a regular expression provides a concise and flexible means for "matching" strings of text, such as particular characters, words, or patterns of characters. Abbreviations for "regular expression" include "regex" and "regexp"...
searches — return numbers, strings, lists, or other non-false values on success, butnil
on failure. This convention is also used in Smalltalk, where only the special objectstrue
andfalse
can be used in a boolean expression. - Versions prior to 1.9 use plain integers to represent single characters, much like CC (programming language)C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
. This may cause surprises when slicing strings:"abc"[0]
yields 97 (the ASCIIASCIIThe American Standard Code for Information Interchange is a character-encoding scheme based on the ordering of the English alphabet. ASCII codes represent text in computers, communications equipment, and other devices that use text...
code of the first character in the string); to obtain"a"
use"abc"[0,1]
(a substring of length 1) or"abc"[0].chr
. - The notation
statement until expression
, like Perl but unlike other languages' equivalent statements (e.g.do { statement } while (!(expression));
in CC (programming language)C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
/C++C++C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
/...), actually never runs the statement if the expression is already true. This is becausestatement until expression
is actually syntactic sugarSyntactic sugarSyntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express....
overuntil expression; statement; end
, the equivalent of which in CC (programming language)C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
/C++C++C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
iswhile (!(expression)) { statement; }
, just asstatement if expression
is equivalent toif (expression) { statement; }
. However, the notationbegin statement end until expression
in Ruby will in fact run the statement once even if the expression is already true, acting similar to the "do-while" of other languages. (Matz has expressed a desire to remove the special behavior ofbegin statement end until expression
, but it still exists as of ruby 1.9.) - Because constants are references to objects, changing what a constant refers to generates a warning, but modifying the object itself does not. For example,
Greeting << " world!" if Greeting "Hello"
does not generate an error or warning. This is similar to final variables in Java or a const pointer to a non-const object in C++C++C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
, but Ruby provides the functionality to "freeze" an object, unlike JavaJava (programming language)Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
.
Some features which differ notably from other languages:
- The usual operators for conditional expressions,
and
andor
, do not follow the normal rules of precedence:and
does not bind tighter thanor
. Ruby also has expression operators||
and&&
which work as expected.
A list of so-called 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.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
: