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...
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...
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 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...
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...
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 ....
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 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 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...
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...
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 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,...
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 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 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...
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...
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....
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 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 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 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 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...
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...
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 ....
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...
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...
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...
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 newsgroup
Newsgroup
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...
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...
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...
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...
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....
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 Rails
Ruby 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 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:
In 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)
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...
A 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...
Internet 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 interface
User 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.
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...
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...
In 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...
In 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...
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...
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...
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
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...
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...
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...
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...
In 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...
In 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....
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....
In computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms...
In 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...
In 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....
In 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...
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:...
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 and nil
Nil
Nil 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 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....
In 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...
In 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 and const_missing)
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...
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...
Unicode 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)
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 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...
RubyGems 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 integer
Integer (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...
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...
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....
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...
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...
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...
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....
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...
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...
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...
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...
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...
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."
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...
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...
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.
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 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...
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 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....
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.
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:...
In 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...
In 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.
In 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 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....
, the expression 0 ? 1 : 0 evaluates to 0 (i.e. false). In Ruby, however, it yields 1, as all numbers evaluate to true; only nil and false evaluate to false. A corollary
Corollary
A 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-expression
Regular expression
In 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, but nil on failure. This convention is also used in Smalltalk, where only the special objects true and false can be used in a boolean expression.
Versions prior to 1.9 use plain integers to represent single characters, much like 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....
. This may cause surprises when slicing strings: "abc"[0] yields 97 (the ASCII
ASCII
The 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 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....
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 because statement until expression is actually syntactic sugar
Syntactic sugar
Syntactic 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....
over until expression; statement; end, the equivalent of which 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....
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...
is while (!(expression)) { statement; }, just as statement if expression is equivalent to if (expression) { statement; }. However, the notation begin 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 of begin 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 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...
.
Some features which differ notably from other languages:
The usual operators for conditional expressions, and and or, do not follow the normal rules of precedence: and does not bind tighter than or. 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:
$ irb
irb(main):001:0> puts "Hello, World"
Hello, World
Examples
The following examples can be run in a Ruby shell such as Interactive Ruby Shell
Interactive Ruby Shell
Interactive 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...
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
"ice is nice".length # 11
"ruby is cool.".index("u") # 1
"Nice Day Isn't It?".downcase.split("").uniq.sort.join # " '?acdeinsty"
Conversions:
puts "What's your favorite number?"
number = gets.chomp
output_number = number.to_i + 1
puts output_number.to_s + ' is a bigger and better favorite number.'
Strings
There are a variety of methods for defining strings in Ruby.
The following assignments are equivalent and support Variable interpolation:
a = "\nThis is a double-quoted string\n"
a = %Q{\nThis is a double-quoted string\n}
a = %{\nThis is a double-quoted string\n}
a = %/\nThis is a double-quoted string\n/
a = <<-BLOCK
This is a double-quoted string
BLOCK
The following assignments are equivalent and produce raw strings:
a = 'This is a single-quoted string'
a = %q{This is a single-quoted string}
In computer science, an array type is a data type that is meant to describe a collection of elements , each selected by one or more indices that can be computed at run time by the program. Such a collection is usually called an array variable, array value, or simply array...
In 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....
(called hashes in Ruby):
hash = { :water => 'wet', :fire => 'hot' }
puts hash[:fire] # Prints: hot
hash.each_pair do |key, value| # Or: hash.each do |key, value|
puts "#{key} is #{value}"
end
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...
:
In an object instance variable (denoted with '@'), remember a block.
def remember(&a_block)
@block = a_block
end
Invoke the above method, giving it a block which takes a name.
remember {|name| puts "Hello, #{name}!"}
When the time is right (for the object) -- call the closure!
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...
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...
from a method:
def create_set_and_get(initial_value=0) # Note the default value of 0
closure_value = initial_value
return Proc.new {|x| closure_value = x}, Proc.new { closure_value }
end
A method such as inject can accept both a parameter and a block. Inject iterates over each member of a list, performing some function on it while retaining an aggregate. This is analogous to the foldl function in functional programming languages. For example:
[1,3,5].inject(10) {|sum, element| sum + element} # => 19
On the first pass, the block receives 10 (the argument to inject) as sum, and 1 (the first element of the array) as element; this returns 11. 11 then becomes sum on the next pass, which is added to 3 to get 14. 14 is then added to 5, to finally return 19.
Blocks work with many built-in methods:
File.open('file.txt', 'w') do |file| # 'w' denotes "write mode".
file.puts 'Wrote some text.'
end # File is automatically closed here
File.readlines('file.txt').each do |line|
puts line
end
=> Wrote some text.
Using an enumeration and a block to square the numbers 1 to 10 (using a range):
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
attr_reader :name, :age
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
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)
Open classes
In Ruby, classes are never closed: you can always add methods to an existing class. This applies to the classes you write as well as the standard, built-in classes. All you have to do is open up a class definition for an existing class, and the new contents you specify will be added to whatever's there. A simple example of adding a new method to the standard library's Time class:
Adding methods to previously defined classes is often called monkey-patching. This practice, however, can lead to possible collisions of behavior and subsequent unexpected results, and is a concern for code scalability if performed recklessly.
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 '#{input}' at line #{line}, position #{pos}"
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. Also supported for use with exceptions are else and ensure
begin
Do something
rescue
Handle exception
else
Do this if no exception was raised
ensure
Do this whether or not an exception was raised
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 -- that 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, Timeout::Error => e
handling, possibly involving e
end
Metaprogramming
Ruby code can programmatically modify, at runtime, aspects of its own structure that would be fixed in more rigid languages, such as class and method definitions. This sort of 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...
can be used to write more concise code and effectively extend the language.
For example, the following Ruby code generates new methods for the built-in String class, based on a list of colors. The methods wrap the contents of the string with an HTML tag styled with the respective color.
The Trabb Pardo–Knuth algorithm is a program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages....
Implementations
The newest version of Ruby, the recently released version 1.9, has a single working implementation written in C that utilizes a Ruby-specific virtual machine.
Ruby version 1.8 has three main implementations: The official Ruby interpreter often referred to as the Matz's Ruby Interpreter
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...
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...
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...
A Java virtual machine is a virtual machine capable of executing Java bytecode. It is the code execution component of the Java software platform. Sun Microsystems stated that there are over 4.5 billion JVM-enabled devices.-Overview:...
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:...
, a reimplementation of Ruby focusing on writing as much of the core in Ruby as possible.
There are other less-known or upcoming implementations such as Cardinal (an implementation for the Parrot virtual machine
Parrot virtual machine
Parrot is a register-based process virtual machine designed to run dynamic languages efficiently. It uses just-in-time compilation for speed to reduce the interpretation overhead. It is currently possible to compile Parrot assembly language and PIR to Parrot bytecode and execute it...
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,...
(alpha version available since July 24, 2008), 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...
MagLev is the name of a 64-bit Ruby virtual machine with an integrated persistent cache developed by GemStone. Based on 's Smalltalk Virtual machine, MagLev compiles Ruby to bytecode, which is then compiled to native machine code using a just-in-time compiler. MagLev was first revealed publicly at...
HotRuby is a Javascript and ActionScript implementation of the Ruby programming language. HotRuby runs Ruby source code on a web browser and Flash...
(runs Ruby source code on a web browser and Flash).
The maturity of Ruby implementations tends to be measured by their ability to run the Ruby on Rails
Ruby on Rails
Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework for the Ruby programming language.-History:...
(Rails) framework, because it is a complex framework to implement, and it uses many Ruby-specific features. The point when a particular implementation achieves this goal is called The Rails singularity. The reference implementation (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...
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 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:...
are all able to run Rails unmodified in a production environment. 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,...
is starting to be able to run Rails test cases, but is still far from being production-ready.
An operating system is a set of programs that manage computer hardware resources and provide common services for application software. The operating system is the most important type of system software in a computer system...
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...
Mac OS X is a series of Unix-based operating systems and graphical user interfaces developed, marketed, and sold by Apple Inc. Since 2002, has been included with all new Macintosh computer systems...
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...
Windows Phone is a mobile operating system developed by Microsoft, and is the successor to its Windows Mobile platform, although incompatible with it. Unlike its predecessor, it is primarily aimed at the consumer market rather than the enterprise market...
Microsoft Windows CE is an operating system developed by Microsoft for embedded systems. Windows CE is a distinct operating system and kernel, rather than a trimmed-down version of desktop Windows...
Unix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...
.
Ruby 1.9 has recently been ported onto Symbian OS 9.x.
Ruby Application Archive is a repository of applications for Ruby programming language development.As of June 2005, it had four categories:* Application: more than 400 projectsTools for development and network middleware, including web frameworks, games,...
RubyForge is a collaborative software development management system dedicated to projects related to the Ruby programming language. It was started in 2003 by Ruby Central in an effort to help the Ruby community by providing a home for open source Ruby projects....
, 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 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...
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...
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 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...
has become the standard package manager for Ruby libraries. It is very similar in purpose to Perl's CPAN
CPAN
CPAN, the Comprehensive Perl Archive Network, is an archive of nearly 100,000 modules of software written in Perl, as well as documentation for it. It has a presence on the World Wide Web at and is mirrored worldwide at more than 200 locations...
, although its usage is more like apt-get.
Recently, many new and existing libraries have found a home on GitHub
Github
GitHub is a web-based hosting service for software development projects that use the Git revision control system. GitHub offers both commercial plans and free accounts for open source projects...
Git is a distributed revision control system with an emphasis on speed. Git was initially designed and developed by Linus Torvalds for Linux kernel development. Every Git working directory is a full-fledged repository with complete history and full revision tracking capabilities, not dependent on...
Programming languages are used for controlling the behavior of a machine . Like natural languages, programming languages conform to rules for syntax and semantics.There are thousands of programming languages and new ones are created every year...
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...
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...
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...
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,...
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:...
XRuby was the first Ruby to Java static compiler which compiles Ruby source code to Java bytecode . It is notable because it contains a complete ANTLR grammar for Ruby 1.8 source code.- See also :* Duck typing...
why's Guide to Ruby, sometimes called wGtR or just "the poignant guide", is an introductory book to the Ruby programming language, written by why the lucky stiff...
The Metasploit Project is an open-source computer security project which provides information about security vulnerabilities and aids in penetration testing and IDS signature development....
- the world's largest Ruby project with over 700,000 lines of code