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 compiler, 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 behaviour. The programming paradigm driven by reflection is called reflective programming.... , general purpose object-oriented programming language
Object-oriented programming language
An object-oriented programming language is one that allows or encourages, to some degree, object-oriented programming techniques such as Information hiding, Inheritance , module , and Polymorphism .... that combines syntax inspired by Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... with Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming 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 learning, at PARC by Al... -like features. Ruby originated in Japan
Japan
Japan is an island country in East Asia. Located in the Pacific Ocean, it lies to the east of the Sea of Japan, People's Republic of 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 initially 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, Ruby MRI.... . It is based on Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... , Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming 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 learning, at PARC by Al... , Eiffel
Eiffel (programming language)
Eiffel is an International Organization for Standardization-standardized, object-oriented programming language designed to enable programmers to efficiently develop extensible, reusable, reliable software.... , Ada
Ada (programming language)
Ada is a structured programming, statically typed, Imperative programming, and Object-oriented programming high-level language computer programming programming language, extended from Pascal and other languages.... , and Lisp.
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 .... s, including functional
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of function s and avoids program state and immutable object data.... , object oriented
Object-oriented programming
Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs.... , imperative
Imperative programming
In computer science, imperative programming is a programming paradigm that describes computation in terms of statement s that change a program state .... and reflective
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming.... . It also has a dynamic type system and automatic memory management
Memory management
Memory management is the act of managing computer memory. In its simpler forms, this involves providing ways to allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed.... ; it is therefore similar in varying respects to Python
Python (programming language)
Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive.... , Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... , Lisp, Dylan, and CLU.
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby . As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference.... is written in C
C (programming language)
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... , as a single-pass interpreted language
Interpreted language
In computer programming an interpreted language is a programming language whose implementation often takes the form of an interpreter . Theoretically, any language may be compiler or interpreted, so this designation is applied purely because of common implementation practice and not some underlying property of a language.... .
Discussion
Ask a question about 'Ruby (programming language)'
Start a new discussion about 'Ruby (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 compiler, 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 behaviour. The programming paradigm driven by reflection is called reflective programming.... , general purpose object-oriented programming language
Object-oriented programming language
An object-oriented programming language is one that allows or encourages, to some degree, object-oriented programming techniques such as Information hiding, Inheritance , module , and Polymorphism .... that combines syntax inspired by Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... with Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming 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 learning, at PARC by Al... -like features. Ruby originated in Japan
Japan
Japan is an island country in East Asia. Located in the Pacific Ocean, it lies to the east of the Sea of Japan, People's Republic of 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 initially 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, Ruby MRI.... . It is based on Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... , Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming 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 learning, at PARC by Al... , Eiffel
Eiffel (programming language)
Eiffel is an International Organization for Standardization-standardized, object-oriented programming language designed to enable programmers to efficiently develop extensible, reusable, reliable software.... , Ada
Ada (programming language)
Ada is a structured programming, statically typed, Imperative programming, and Object-oriented programming high-level language computer programming programming language, extended from Pascal and other languages.... , and Lisp.
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 .... s, including functional
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of function s and avoids program state and immutable object data.... , object oriented
Object-oriented programming
Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs.... , imperative
Imperative programming
In computer science, imperative programming is a programming paradigm that describes computation in terms of statement s that change a program state .... and reflective
Reflection (computer science)
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming.... . It also has a dynamic type system and automatic memory management
Memory management
Memory management is the act of managing computer memory. In its simpler forms, this involves providing ways to allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed.... ; it is therefore similar in varying respects to Python
Python (programming language)
Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive.... , Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... , Lisp, Dylan, and CLU.
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby . As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference.... is written in C
C (programming language)
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... , as a single-pass interpreted language
Interpreted language
In computer programming an interpreted language is a programming language whose implementation often takes the form of an interpreter . Theoretically, any language may be compiler or interpreted, so this designation is applied purely because of common implementation practice and not some underlying property of a language.... . There is currently no specification of the Ruby language, so the original implementation is considered to be the de facto reference. As of 2008, there are a number of complete or upcoming alternative implementations of the Ruby language, including YARV
YARV
YARV is a bytecode interpreter that was developed for the Ruby programming language by Koichi Sasada. The name is an acronym for Yet another Ruby VM.... , JRuby
JRuby
JRuby is a Java implementation of the Ruby , being developed by the JRuby team.JRuby is free software released under a three-way Common Public License/GNU General Public License/GNU Lesser General Public License license.... , Rubinius
Rubinius
Rubinius is an alternative Ruby implementation created by Evan Phoenix. Based loosely on the Smalltalk-80 Blue Book design, Rubinius seeks to... , IronRuby
IronRuby
IronRuby is an upcoming implementation of the Ruby targeting Microsoft .NET framework. It is implemented on top of the Dynamic Language Runtime, a library running on top of Common Language Runtime 2.0 that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages.... , and MacRuby
MacRuby
MacRuby is an implementation of the Ruby language that runs on the Objective-C runtime under development by Apple Inc. which "is supposed to replace RubyCocoa".... , each of which takes a different approach, with JRuby and IronRuby providing just-in-time compilation
Just-in-time compilation
In computing, just-in-time compilation , also known as dynamic translation, is a technique for improving the runtime performance of a computer program.... . 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 name is an acronym for Yet another Ruby VM.... , 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 . As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference.... .
is a Japanese computer scientist and software programmer best known as the chief designer of the Ruby programming language and its reference implementation, Ruby MRI.... who wished to create a new language that balanced functional programming with imperative programming. According to Matsumoto he "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".
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
Coral
Corals are marine organisms from the class Anthozoa and exist as small sea anemone?like polyps, typically in colonies of many identical individuals.... " and "Ruby", with the latter the one being chosen as the name 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. Later it was recognized that pearl
Pearl
A pearl is a hard, roundish object produced within the soft tissue of a living animal shelled mollusk. Just like the shell of mollusks, a pearl is made up of of calcium carbonate in minute crystalline form, which has been deposited in concentric layers.... is the birthstone for the month of June, while ruby
Ruby
A ruby is a pink to blood-red gemstone, a variety of the mineral corundum . The red color is caused mainly by the presence of the element chromium.... is the birthstone for July, implying Ruby as the successor of Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... .
First publication
The first public release of Ruby 0.95 was announced on Japanese domestic newsgroup
Newsgroup
A newsgroup is a repository usually within the Usenet system, for messages Posting style from many users in different locations. The term may be confusing to some, because it is usually a discussion group.... 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 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 programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share.... with inheritance, mixin
Mixin
In object-oriented programming languages, a mixin is a class that provides a certain functionality to be Inheritance by a subclass, but is not meant to stand alone.... s, iterator
Iterator
In computer science, an iterator is an object that allows a programmer to traverse through all the elements of a Collection , regardless of its specific implementation.... s, closure
Closure (computer science)
In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these 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 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 used by Object that will never be accessed or mutated again by the Application software.... .
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 began, which signaled 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 Andy 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 to the public further widening the adoption of Ruby amongst native English speakers.
Ruby 1.9.1
As of 30 January 2009, the latest stable version of the reference implementation is 1.9.1.
Ruby 1.9.1 introduces a lot of changes compared to version 1.8.6, such as:
In computer science, a local variable is a variable that is given local scope . Such a variable is accessible only from the subroutine or statement block in which it is declared.... variables (variables that are local to the block
Statement block
In computer programming, a statement block is a section of computer code which is grouped together, much like a paragraph; such blocks consist of one, or more, statement .... in which they are declared)
A character encoding system consists of a code that pairs a sequence of character from a given character set with something else, such as a sequence of natural numbers, octet or electrical pulses, in order to facilitate the transmission of data through telecommunication networks and/or Computer data storage of Character in compute... s are supported
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 is the aggregate of means by which people—the User s—Interaction with the system—a particular machine, device, computer program or other complex tools.... design. He stresses that systems design needs to emphasize human, rather than computer, needs:
Ruby is said to follow the principle of least surprise (POLS), meaning that the language should behave in such a way as to minimize confusion for experienced users. Matsumoto has said his primary design goal was to make a language which he himself enjoyed using, by minimizing programmer work and possible confusion. He has said he had not applied the principle of least surprise to the design of Ruby, but nevertheless the phrase has come to be closely associated with the Ruby programming language. The phrase has itself been a source of surprise, as novice users may take it to mean that Ruby's behaviors try to closely match behaviors familiar from other languages. In a May 2005 discussion on the comp.lang.ruby newsgroup, Matsumoto attempted to distance Ruby from POLS, explaining that because any design choice will be surprising to someone, he uses a personal standard in evaluating surprise. If that personal standard remains consistent there will be few surprises for those familiar with the standard.
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.... , class
Class variable
In object-oriented programming with Class es, a class variable is a variable defined in a Class of which a single copy exists, regardless of how many objects of the class exist.... , class instance, instance
Instance variable
In object-oriented programming with Class es, an instance variable is a variable defined in a class, for which each object in the class has a separate copy.... , local
Local variable
In computer science, a local variable is a variable that is given local scope . Such a variable is accessible only from the subroutine or statement block in which it is declared.... , and block
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 execution....
In computer science, an iterator is an object that allows a programmer to traverse through all the elements of a Collection , regardless of its specific implementation.... s and closures
Closure (computer science)
In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables.... (based on passing blocks of code)
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... -like regular expression
Regular expression
In computing, regular expressions provide a concise and flexible means for identifying strings of text of interest, such as particular characters, words, or patterns of characters.... s at the language level
In computer programming, operator overloading is a specific case of polymorphism in which some or all of operator s like +, =, or have different implementations depending on the types of their arguments....
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage , or memory used by Object that will never be accessed or mutated again by the Application software....
In computer science, porting is the process of adapting software so that an executable Computer program can be created for a computing environment that is different from the one for which it was originally designed ....
Cooperative multi-threading on all platforms using green threads
Green threads
In computer programming, green threads are thread that are scheduled by a Virtual Machine instead of natively by the underlying operating system....
Dynamic-link library , or DLL, is Microsoft's implementation of the shared library concept in the Microsoft Windows and OS/2 operating systems.... /Shared library
Library (computer science)
In computer science, a library is a collection of subroutines or Class used to develop software. Libraries contain code and data that provide services to independent programs.... dynamic loading on most platforms
In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour. The programming paradigm driven by reflection is called reflective programming.... 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 runtime that would otherwise be done at compile time....
Dependency Injection in computer programming refers to the process of supplying an Coupling to a software component. It is a specific form of inversion of control where the concern being inverted is the process of obtaining the needed dependency....
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 compiler, if at all....
In computing and programming, a continuation is an abstract representation of Control flow, or the "rest of computation" or "rest of code to be executed".... s and generators
Generator (computer science)
In computer science, a generator is a special subroutine that can be used to control the iteration behaviour of a control flow#Loops. 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....
Unicode is a computing industry standard allowing computers to consistently represent and manipulate Character expressed in most of the world's writing systems.... , though it has partial support for UTF-8
UTF-8
UTF-8 is a Variable-width encoding character encoding for Unicode. It is able to represent any character in the Unicode standard, yet the initial encoding of byte codes and character assignments for UTF-8 is backward compatibility with ASCII.... .
Semantics
Ruby is object-oriented: every data type is an object, including classes and types which many other languages designate as primitives (such as integer
Integer (computer science)
In computer science, the term integer is used to refer to a data type which represents some finite subset of the mathematical integers. These are also known as integral data types.... s, booleans, and "nil"). Every function is a method. Named values (variables) always designate references to objects, not the objects themselves. Ruby supports inheritance with dynamic dispatch
Dynamic dispatch
In computer science, dynamic dispatch is the process of mapping a Message passing to a specific sequence of code at runtime. This is done to support the cases where the appropriate method cannot be determined at compile-time .... , mixin
Mixin
In object-oriented programming languages, a mixin is a class that provides a certain functionality to be Inheritance by a subclass, but is not meant to stand alone.... 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
Multiple inheritance
Multiple inheritance refers to a feature of some object-oriented programming programming languages in which a class can inheritance behaviors and features from more than one superclass .... , classes can import modules as mixins. Procedural syntax is supported, but all methods defined outside of the scope of a particular object are actually methods of the Object class. Since this class is parent to every other class, the changes become visible to all classes and objects.
A multi-paradigm programming language is a programming language that supports more than one programming paradigm. As Lead designer Tim Budd holds it: The idea of a multiparadigm language is to provide a framework in which programmers can work in a variety of styles, freely intermixing constructs from different paradigms. The design goal... : 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 function s and avoids program state and immutable object data.... (it has anonymous function
Anonymous function
In computing, an anonymous function is a function defined, and possibly called, without being bound to a name. In lambda calculus, all functions are anonymous.... s, closures
Closure (computer science)
In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables.... , and continuation
Continuation
In computing and programming, a continuation is an abstract representation of Control flow, or the "rest of computation" or "rest of code to be executed".... 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 behaviour. The programming paradigm driven by reflection is called reflective programming.... 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 runtime that would otherwise be done at compile time.... , as well as support for interpreter-based thread
Thread (computer science)
In computer science, a thread of execution is a Fork of a computer program into two or more Concurrency running task s. The implementation of threads and process es 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
In computer science, a type system may be defined as "a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they compute.".... , and supports parametric polymorphism.
Frequently Asked Questions, or FAQs are listed questions and answers, all supposed to be frequently asked in some context, and pertaining to a particular topic.... , "If you like Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... , you will like Ruby and be right at home with its syntax. If you like Smalltalk
Smalltalk
Smalltalk is an Object-oriented programming, Type system, reflection computer programming 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 learning, at PARC by Al... , 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. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the 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 Perl and Python. 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 . The term was first applied to Perl usage by Philip Gwyn in 1999 to replace the more cumbersome "funny character in front of a variable name".... . When used, the sigil changes the semantics of scope of the variable. The most striking difference from C and Perl is that keywords are typically used to define logical code blocks, without braces (i.e., pair of ). For practical purposes there is no distinction between expressions
Expression (programming)
An expression in a programming language is a combination of value s, variables, operator s, and function s that are interpreted according to the particular Order of operations 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 is formed by a sequence of one or more statements.... statement [...] can not be part of expression unless grouped within parentheses. http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/2460 . Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Unlike Python, indentation is not significant.
One of the differences of Ruby compared to Python and Perl is that Ruby keeps all of its instance variables completely private to the class and only exposes them through accessor methods (attr_writer, attr_reader, etc). Unlike the "getter" and "setter" methods of other languages like C++ or Java, accessor methods in Ruby 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 removes this design decision by forcing all instance variables to be private, but also provides a simple way to declare set and get methods. This is in keeping with the idea that in Ruby, one never directly accesses the internal members of a class from outside of it. Rather one passes a message to the class and receives a response.
See the examples section for samples of code demonstrating Ruby syntax.
"Gotchas"
Language comparison
Some features which differ notably from languages such as C
C (programming language)
C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system.... or Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... :
Names which begin with a capital letter are treated as constants, so local variables should begin with a lowercase letter.
In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype or Scope . The term was first applied to Perl usage by Philip Gwyn in 1999 to replace the more cumbersome "funny character in front of a variable name".... $ and @ do not indicate variable data type
Data type
A data type in programming languages is an attribute of a data which tells the computer something about the kind of data it is. This involves setting constraints on the datum, such as what values it can take and what operations may be performed upon it.... as in Perl, but rather function as scope resolution operator
Scope resolution operator
The scope resolution operator in C++ is used to define the already declared member functions of the class. In the .cpp file one can define the normal functions or the member functions of the class.... 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 algebra datatype, sometimes called the logical datatype, is a primitive datatype having one of two values: Truth value and false.... evaluation of non-boolean data is strict: 0, "" and [] are all evaluated to true. In C, the expression 0 ? 1 : 0 evaluates to 0 (i.e. false). In Ruby, however, it yields 1, as all numbers evaluate to true; only nil and false evaluate to false. A corollary
Corollary
A corollary is a statement which follows readily from a previously proven 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, regular expressions provide a concise and flexible means for identifying strings of text of interest, such as particular characters, words, or patterns of characters.... 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 lack a character data type (compare to C, which provides type char for characters). This may cause surprises when slicing strings: "abc"[0] yields 97 (the ASCII
ASCII
American Standard Code for Information Interchange , is a coding standard that can be used for interchanging information, if the information is expressed mainly by the written form of English words.... 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, unlike other languages' equivalent statements (e.g. do while (!(expression)); in C/C++/...), 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 term coined by Peter J. Landin for additions to the syntax of a computer language that do not affect its Function but make it "sweeter" for humans to use.... over until expression; statement; end, the equivalent of which in C/C++ is while (!(expression)) , just like statement if expression is an equivalent to if (expression) . 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.
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++, but Ruby provides the functionality to "freeze" an object, unlike Java or C++.
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.
Language features
Omission of parentheses around method arguments may lead to unexpected results if the methods take multiple parameters. The Ruby developers have stated that omission of parentheses on multi-parameter methods may be disallowed in future Ruby versions; the current (November 2007) Ruby interpreter throws a warning which encourages the writer not to omit , to avoid ambiguous meaning of code. Not using is still common practice, and can be especially nice to use Ruby as a human readable domain-specific programming language
Domain-specific programming language
In software development, a domain-specific language is a programming language or specification language dedicated to a particular problem domain, a particular problem representation technique, and/or a particular solution technique.... itself, along with the method called method_missing.
A list of "gotchas" may be found in Hal Fulton's book The Ruby Way, 2nd ed (ISBN 0-672-32884-4), Section 1.5. A similar list in the 1st edition pertained to an older version of Ruby (version 1.6), some problems of which have been fixed in the meantime. retry, for example, now works with while, until, and for, as well as iterators.
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:
Interactive Ruby Shell is a shell for programming in the Object-oriented programming scripting language Ruby programming language. IRB is run from the Command line interface and allows the programmer to experiment with code 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
"ruby is cool".length # 12
"Your mother is nice.".index("u") # 2
"Nice Day Isn't It?".downcase.split(//).sort.uniq.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 of defining strings in Ruby
The below conventions are equivalent for double quoted strings:
a = "\nThis is a double quoted string\n"
a = %Q
a = < This is a multi-line double quoted string
BLOCK
a = %/\nThis is a double quoted string\n/
The below conventions are equivalent for single quoted strings:
a = 'This is a single quoted string'
a = %q
In computer science, an array is a data structure consisting of a group of element s that are accessed by index . In most programming languages each element has the same data type and the array occupies a contiguous area of computer memory.... :
a = [1, 'hi', 3.14, 1, 2, [4, 5]]
p a[2] # 3.14
p a.[](2)# 3.14
p a.reverse # 4, 5], 2, 1, 3.14, 'hi', 1]
p a.flatten.uniq # [1, 'hi', 3.14, 2, 4, 5]
An associative array is an abstract data type composed of a Collection of unique keys and a collection of values, where each key is associated with one value .... :
hash =
puts hash[:fire] # Prints: hot
hash.each_pair do |key, value| # Or: hash.each do |key, value|
puts "# is #"
end
In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these 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
When the time is right (for the object) -- call the closure!
In computer science, a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these 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
You can also use a parameter variable as a binding for the closure. So the above can be rewritten as...
def create_set_and_get(closure_value=0)
proc
end
Yielding the flow of program control to a block which was provided at calling time:
def use_hello
yield "hello"
end
Invoke the above method, passing it a block.
use_hello
'hello'
>
Iterating over enumerations and arrays using blocks:
array = [1, 'hi', 3.14]
array.each
# => 1
=> 'hi'
=> 3.14
array.each_index
# => 0: 1
=> 1: 'hi'
=> 2: 3.14
(3..6).each
# => 3
=> 4
=> 5
=> 6
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 while retaining an aggregate. This is analogous to the foldl function in functional programming languages. For example:
[1,3,5].inject(10)
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:
(1..10).collect
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>
Classes
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)
Exceptions
An exception is raised with a raise call:
raise
An optional message can be added to the exception:
raise "This is a message"
You can also specify which type of exception you want to raise:
raise ArgumentError, "Illegal arguments!"
Alternatively, you can pass an exception instance to the raise method:
raise ArgumentError.new("Illegal arguments!")
This last construct is useful when you need to raise a custom exception class featuring a constructor which takes more than one argument:
class ParseError < Exception
def initialize input, line, pos
super "Could not parse '#' at line #, position #"
end
end
raise ParseError.new("Foo", 3, 9)
Exceptions are handled by the rescue clause. Such a clause can catch exceptions which inherit from StandardError:
begin
Do something
rescue
Handle exception
end
It is a common mistake to attempt to catch all exceptions with a simple rescue clause. To catch all exceptions one must write:
begin
Do something
rescue Exception # don't write just rescue -- 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, TimeoutError => e
handling, possibly involving e
end
Or catch an array of exceptions:
array_of_exceptions = [RuntimeError, TimeoutError]
begin
...
rescue *array_of_exceptions => e
handling, possibly involving e
end
Metaprogramming
Ruby provides a programmer the ability to add to or modify methods in the language's Standard Library
Standard library
A standard library for a programming language is the library that is conventionally made available in every implementation of that language. In some cases, the library is described directly in the programming language specification; in other cases, the contents of the standard library are determined by more informal social practices in the... during runtime
Runtime
In computer science, runtime or run time describes the operation of a computer program, the duration of its execution, from beginning to termination .... , as well for a Ruby program to modify itself during its operation without generating source code, techniques known as 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 runtime that would otherwise be done at compile time.... . A simple example of adding a new method to the Standard Library's Time class:
The Trabb Pardo-Knuth algorithm is a computer program introduced by Donald Knuth and Luis Trabb Pardo to illustrate the evolution of computer programming languages....
Implementations
Ruby has two 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 . As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference.... or MRI, which is the most widely used, and JRuby
JRuby
JRuby is a Java implementation of the Ruby , being developed by the JRuby team.JRuby is free software released under a three-way Common Public License/GNU General Public License/GNU Lesser General Public License license.... , a 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 .... -based implementation that runs on the Java Virtual Machine
Java Virtual Machine
A Java Virtual Machine is a set of computer software programs and data structures which use a virtual machine model for the execution of other computer programs and Scripting language.... .
There are other less known or upcoming implementations such as IronRuby
IronRuby
IronRuby is an upcoming implementation of the Ruby targeting Microsoft .NET framework. It is implemented on top of the Dynamic Language Runtime, a library running on top of Common Language Runtime 2.0 that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages.... (alpha
Development stage
A software release is the distribution of an initial or upgraded Software versioning of a computer software product. The software engineering and company doing the work decide on how to distribute the program or system, or changes to that program or system.... version available since July 24, 2008), Rubinius
Rubinius
Rubinius is an alternative Ruby implementation created by Evan Phoenix. Based loosely on the Smalltalk-80 Blue Book design, Rubinius seeks to... , , , YARV
YARV
YARV is a bytecode interpreter that was developed for the Ruby programming language by Koichi Sasada. The name is an acronym for Yet another Ruby VM.... , Cardinal
Parrot virtual machine
Parrot is a register machine virtual machine being developed using the C and intended to run dynamic languages efficiently. It uses just-in-time compilation for speed to reduce the interpretation overhead.... and MagLev
MagLev (Ruby interpreter)
MagLev is the name of an upcoming Ruby virtual machine under development by GemStone Systems. MagLev compiles Ruby to bytecode, which is then compiled on the fly to native machine code using a just-in-time compiler.... . YARV is Ruby 1.9's official new virtual machine and is no longer a separate project.
The maturity of Ruby implementations tend to be measured by their ability to run Rails
Ruby on Rails
Ruby on Rails is an open source web application framework for the Ruby . It is often referred to as "Rails" or "RoR". It is intended to be used with an agile software development, which is often utilized by web developers for its suitability for short, client-driven projects.... (because this is a complex framework to implement, and it uses a lot of Ruby-specific features). The point when a particular implementation achieves this goal is called The Rails singularity. As of January 2009, only the reference implementation (MRI)
Ruby MRI
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby . As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference.... and JRuby
JRuby
JRuby is a Java implementation of the Ruby , being developed by the JRuby team.JRuby is free software released under a three-way Common Public License/GNU General Public License/GNU Lesser General Public License license.... are able to run Rails unmodified in a production environment. IronRuby
IronRuby
IronRuby is an upcoming implementation of the Ruby targeting Microsoft .NET framework. It is implemented on top of the Dynamic Language Runtime, a library running on top of Common Language Runtime 2.0 that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages.... and Rubinius
Rubinius
Rubinius is an alternative Ruby implementation created by Evan Phoenix. Based loosely on the Smalltalk-80 Blue Book design, Rubinius seeks to... start to be able to run Rails test cases, but they still are far from production ready for this task.
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby . As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference.... , Ruby is available on a lot of operating system
Operating system
An operating system is an interface between hardware and applications; it is responsible for the management and coordination of activities and the sharing of the limited resources of the computer.... s such as Linux
Linux
Linux is a generic term referring to Unix-like computer operating systems based on the Linux kernel. Their development is one of the most prominent examples of free and open source software collaboration; typically all the underlying source code can be used, freely modified, and redistributed by anyone under the terms of the GNU GPL license... , Mac OS X
Mac OS X
Mac OS X is a line of computer operating systems developed, marketed, and sold by Apple Inc., and since 2002 has been included with all new Macintosh computer systems.... , Microsoft Windows
Microsoft Windows
Microsoft Windows is a series of software operating systems and graphical user interfaces produced by Microsoft. Microsoft first introduced an operating environment named Windows in November 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces .... , Windows CE
Windows CE
Windows CE is Microsoft's operating system for minimalistic computers and embedded systems. Windows CE is a distinctly different operating system and Kernel , rather than a trimmed-down version of desktop Windows.... and most flavors of Unix
Unix
Unix is a computer operating system originally developed in 1969 by a group of American Telephone & Telegraph employees at Bell Labs, including Ken Thompson , Dennis Ritchie, Douglas McIlroy, and Joe Ossanna.... .
Ruby 1.9 has recently been ported onto Symbian OS 9.x.
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby . As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference.... is generally considered the de facto reference specification, however work for a specification is officially ongoing with a project named RubySpec based on the work started by the Rubinius
Rubinius
Rubinius is an alternative Ruby implementation created by Evan Phoenix. Based loosely on the Smalltalk-80 Blue Book design, Rubinius seeks to... project. The creator of Ruby has expressed his plans to make Ruby an ISO standard, which he deems will take some time to be completed.
Ruby code runs slower than many comparable scripting languages, such as Python
Python (programming language)
Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive.... and Perl
Perl
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... . However Ruby 1.9.1, officially released in January 2009, has a speed increase of roughly twice that of Ruby 1.8, being bytecode compiled
Bytecode
Bytecode is a term which has been used to denote various forms of instruction sets designed for efficient execution by a software Interpreter as well as being suitable for further compilation into machine language.... and executed on YARV
YARV
YARV is a bytecode interpreter that was developed for the Ruby programming language by Koichi Sasada. The name is an acronym for Yet another Ruby VM.... .
Metaprogramming is the writing of computer programs that write or manipulate other programs as their data, or that do part of the work at runtime that would otherwise be done at compile time.... has been criticized for allowing a programmer to modify or add methods to the language's Standard Library
Standard library
A standard library for a programming language is the library that is conventionally made available in every implementation of that language. In some cases, the library is described directly in the programming language specification; in other cases, the contents of the standard library are determined by more informal social practices in the... during runtime, a practice known as monkey patching. This can lead to possible collisions of behavior and subsequent unexpected results, and is a concern for code scalability if performed recklessly.
In computer programming, green threads are thread that are scheduled by a Virtual Machine instead of natively by the underlying operating system.... instead of native threading. Ruby 1.9 does use native threading however is dependent on a GIL
Global Interpreter Lock
Global Interpreter Lock is a mutual exclusion lock held by a programming language interpreter Thread to avoid sharing code that is not thread-safe with other threads.... .
Unicode is a computing industry standard allowing computers to consistently represent and manipulate Character expressed in most of the world's writing systems.... or multibyte strings, although this has been implemented in Ruby 1.9.
Ruby has not maintained full backwards compatibility through version 1.9.
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 projects... (RAA), as well as RubyForge
RubyForge
RubyForge is a collaborative Forge dedicated to projects related Ruby programming language. It was started in 2003 by Ruby_Central in an effort to help 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
In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language.... or Python
Python (programming language)
Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the 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 library , a tool designed to easily manage the installation of gems, and a server for distributing them.... 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 over 14,800 modules of software written in Perl, as well as documentation for it.... , although its usage is more like apt-get.
In computer programming, duck typing is a style of dynamic typing in which an object's current set of Method s and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface....
Programming languages are used for controlling the behavior of a machine . Like natural languages, programming languages conform to rules for syntax and semantics....
Matz's Ruby Interpreter or Ruby MRI is the reference implementation of the Ruby . As there is currently no specification of the Ruby language, the MRI implementation is considered the de facto reference.... , the reference C implementation
JRuby is a Java implementation of the Ruby , being developed by the JRuby team.JRuby is free software released under a three-way Common Public License/GNU General Public License/GNU Lesser General Public License license....
MacRuby is an implementation of the Ruby language that runs on the Objective-C runtime under development by Apple Inc. which "is supposed to replace RubyCocoa"....
IronRuby is an upcoming implementation of the Ruby targeting Microsoft .NET framework. It is implemented on top of the Dynamic Language Runtime, a library running on top of Common Language Runtime 2.0 that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages....
XRuby was the first Ruby programming language 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....
Ruby on Rails is an open source web application framework for the Ruby . It is often referred to as "Rails" or "RoR". It is intended to be used with an agile software development, which is often utilized by web developers for its suitability for short, client-driven projects....
The Open Directory Project , also known as Dmoz , is a multilingual open content Web directory of World Wide Web links owned by Netscape that is constructed and maintained by a virtual community of volunteer editors....
By Matz, the creator of Ruby. Translated into English.