
- Order:
- Duration: 3:52
- Published: 2009-09-22
- Uploaded: 2011-01-09
- Author: SapphireSteelDotCom
these configurations will be saved for each time you visit this page using this browser
Ruby supports multiple programming paradigms, including functional, object oriented, imperative and reflective. It also has a dynamic type system and automatic memory management; it is therefore similar in varying respects to Python, Perl, Lisp, Dylan, Pike, and CLU.
The standard 1.8.7 implementation is written in C, as a single-pass interpreted language. There is currently no specification of the Ruby language, so the original implementation is considered to be the de facto reference. , there are a number of complete or upcoming alternative implementations of the Ruby language, including YARV, JRuby, Rubinius, IronRuby, MacRuby, and HotRuby. Each takes a different approach, with IronRuby, JRuby and MacRuby providing just-in-time compilation and MacRuby also providing ahead-of-time compilation. The official 1.9 branch uses YARV, as will 2.0 (development), and will eventually supersede the slower Ruby MRI.
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."
Ruby 1.9 introduces many significant changes over the 1.8 series. Some examples are:
fun = ->(a,b) { puts a + b }
)Ruby is said to follow the principle of least astonishment (POLA), meaning that the language should behave in such a way as to minimize confusion for experienced users. Matsumoto has said his primary design goal was to make a language which he himself enjoyed using, by minimizing programmer work and possible confusion. He has said that he had not applied the principle of least surprise to the design of Ruby,
Matsumoto defined it this way in an interview:
false
and nil
)method_missing
and const_missing
)Ruby has been described as a multi-paradigm programming language: it allows procedural programming (defining functions/variables outside classes makes them part of the root, 'self' Object), with object orientation (everything is an object) or functional programming (it has anonymous functions, closures, and continuations; statements all have values, and functions return the last evaluation). It has support for introspection, reflection and metaprogramming, as well as support for interpreter-based threads. Ruby features dynamic typing, and supports parametric polymorphism.
According to the Ruby FAQ, "If you like Perl, you will like Ruby and be right at home with its syntax. If you like Smalltalk, you will like Ruby and be right at home with its semantics. If you like Python, you may or may not be put off by the huge difference in design philosophy between Python and Ruby/Perl."
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.
* The language syntax is sensitive to the capitalization of identifiers, in most cases treating capitalized variables as constants.
$
and @
do not indicate variable data type as in Perl, but rather function as scope resolution operators.99.0
) or an explicit conversion (99.to_f
). It is insufficient to append a dot (99.
) since numbers are susceptible to method syntax.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 to this rule is that Ruby methods by convention — for example, regular-expression 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."abc"[0]
yields 97 (the ASCII code of the first character in the string); to obtain "a"
use "abc"[0,1]
(a substring of length 1) or "abc"[0].chr
.statement until expression
, unlike other languages' equivalent statements (e.g. do { statement } 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 over until expression; statement; end
, the equivalent of which in C/C++ 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.)
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.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.
irb
", an interactive command-line interpreter which can be used to test code quickly. The following code fragment represents a sample session using irb
:
ruby
.
Classic Hello world example:
Some basic Ruby code:
Conversions:
The following assignments are equivalent and support Variable interpolation:
This is a double-quoted string BLOCK
The following assignments are equivalent and produce raw strings:
Constructing and using an [[associative array (called hashes in Ruby):
hash.each_pair do |key, value| # Or: hash.each do |key, value| puts "#{key} is #{value}" end
# Prints: water is wet # fire is hothash.delete :water # Deletes :water => 'wet' hash.delete_if {|key,value| value=='hot'} # Deletes :fire => 'hot'
When a code block is created it is always attached to a method as an optional block argument.
Parameter-passing a block to be a closure:
# When the time is right (for the object) -- call the closure! @block.call("Jon") # => "Hello, Jon!"
Creating an anonymous function:
Returning closures from a method:
setter, getter = create_set_and_get # ie. returns two values setter.call(21) getter.call # => 21
#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 {|x| closure_value = x } , proc { closure_value } end
Yielding the flow of program control to a block which was provided at calling time:
Iterating over enumerations and arrays using blocks:
array.each_index {|index| puts "#{index}: #{array[index]}" } # => 0: 1 # => 1: 'hi' # => 2: 3.14
# The following uses a Range (3..6).each {|num| puts num } # => 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 it while retaining an aggregate. This is analogous to the foldl function in functional programming languages. For example:
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.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):
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'.
puts group.sort.reverse
The above prints three names in reverse age order:
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.
raise
call:
An optional message can be added to the exception:
You can also specify which type of exception you want to raise:
Alternatively, you can pass an exception instance to the raise method:
This last construct is useful when you need to raise a custom exception class featuring a constructor which takes more than one argument:
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
It is a common mistake to attempt to catch all exceptions with a simple rescue clause. To catch all exceptions one must write:
Or catch particular exceptions:
It is also possible to specify that the exception object be made available to the handler clause:
Alternatively, the most recent exception is stored in the magic global $!
.
You can also catch several exceptions:
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 generated methods could then be used like so:
To implement the equivalent in many other languages, the programmer would have to write each method (in_black, in_red, in_green, etc.) by hand.
Some other possible uses for Ruby metaprogramming include:
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 two main implementations: The official Ruby interpreter often referred to as the Matz's Ruby Interpreter or MRI, which is the most widely used, and JRuby, a Java-based implementation that runs on the Java Virtual Machine.
There are other less-known or upcoming implementations such as Cardinal (an implementation for the Parrot virtual machine), IronRuby (alpha version available since July 24, 2008), MacRuby, MagLev, Rubinius, Ruby.NET, XRuby and HotRuby (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 (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. As of May 2010, only the reference implementation (MRI) and JRuby are able to run Rails unmodified in a production environment. Rubinius recently released 1.0 and can run Rails, but should not be used for production sites yet. IronRuby is starting to be able to run Rails test cases, but is still far from being production-ready.
Ruby is available on many operating systems such as Linux, Mac OS X, Microsoft Windows, Windows Phone 7, Windows CE and most flavors of Unix.
Ruby 1.9 has recently been ported onto Symbian OS 9.x.
RubyGems has become the standard package manager for Ruby libraries. It is very similar in purpose to Perl's CPAN, although its usage is more like apt-get.
Recently, many new and existing libraries have found a home on GitHub, which is focused on Git and used to have native support for RubyGems packaging.
Category:Class-based programming languages Category:Dynamically typed programming languages Category:Scripting languages Category:Object-oriented programming languages Category:Articles with example Ruby code Category:Programming languages created in 1995
This text is licensed under the Creative Commons CC-BY-SA License. This text was originally published on Wikipedia and was developed by the Wikipedia community.