| Ruby |
|
|
|
Ruby is a dynamic, reflective, general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was initially developed and designed by Yukihiro "Matz" Matsumoto. Ruby supports multiple programming paradigms, including functional, object oriented, imperative and reflection. It also has a dynamic type system and automatic memory management; it is therefore similar in varying respects to Python, Perl, Lisp, Dylan, and CLU. In its current, official implementation, written in C, Ruby is 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. As of 2008, there are a number of complete or upcoming alternative implementations of the Ruby language, including YARV, JRuby, Rubinius, IronRuby, and MacRuby, each of which takes a different approach, with JRuby and IronRuby providing just-in-time compilation functionality. HistoryThe language was created by Yukihiro Matsumoto, who started working on Ruby on February 24, 1993, and released it to the public in 1995. "Ruby" was named as a gemstone because of a joke within Matsumoto's circle of friends alluding to the name of the Perl programming language. As of June 2008, the latest stable version of the reference implementation is 1.8.7. Apart from the reference, several other virtual machines are being developed for Ruby. These include JRuby, a port of Ruby to the Java platform, IronRuby, an implementation for the .NET Framework produced by Microsoft, and Rubinius, an interpreter modeled after self-hosting Smalltalk virtual machines. PhilosophyThe language's creator, Yukihiro "Matz" Matsumoto, has said that Ruby is designed for programmer productivity and fun, following the principles of good user interface design.[2] He stresses that systems design needs to emphasize human, rather than computer, needs.
Ruby is said to follow the principle of least surprise (POLS), meaning that the language should behave in such a way as to minimize confusion for experienced users. Matsumoto has said his primary design goal was to make a language which he himself enjoyed using, by minimizing programmer work and possible confusion. He has said he had not applied the principle of least surprise to the design of Ruby, but nevertheless the phrase has come to be closely associated with the Ruby programming language. The phrase has itself been a source of surprise, as novice users may take it to mean that Ruby's behaviors try to closely match behaviors familiar from other languages. In a May 2005 discussion on the comp.lang.ruby newsgroup, Matsumoto attempted to distance Ruby from POLS, explaining that because any design choice will be surprising to someone, he uses a personal standard in evaluating surprise. If that personal standard remains consistent there will be few surprises for those familiar with the standard. Matsumoto defined it this way in an interview:
SemanticsRuby is object oriented: every data type is an object, including classes and types which many other languages designate as primitives (such as integers, 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, mixins and singleton methods (belonging to, and defined for, a single instance rather than being defined on the class). Though Ruby does not support multiple inheritance, classes can import modules as mixins. 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. 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[7] 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." Type systemRuby never inherently checks the type of any expression entered in code; rather, if a method deems a type error to have occurred, then it raises a TypeError. To demonstrate this point, the code 1 + "a" results in a TypeError (String can't be coerced into Fixnum), but this is not an inherent or unchangeable property; we could, should we desire, redefine the method Fixnum#+ to not throw a TypeError, but do something else. Ruby never checks the type with intent; only the program code does. Another error of type occurs when a method is called that doesn't exist (the object does not have the expected type, be the properties of that type inherited from class or added at runtime). Is Ruby type safe?"Type safety" has no universally agreed upon definition. Whether or not Ruby is "type safe" depends on which definition is applied. One definition of "type-safe language" requires that: "No operation will be applied to a variable of a wrong type." In this respect, Ruby is probably type safe. Although Ruby's semantics make such an assertion very difficult to prove theoretically, it could be assumed so long as no contradictory code example can be found. Another definition of a "type-safe program" requires that: "The program will not have type errors when it runs." In this respect, Ruby is obviously not type safe, since, by design, a Ruby program can raise type errors (via the TypeError exception class) during execution. Is Ruby strongly typed?Again, there is no universally agreed upon definition of "strongly typed". C2.com Wiki lists at least 8 different definitions from different sources. According to some of these definitions, Ruby is strongly typed, while according to others it is weakly typed:
Types vs. classesIn Ruby, the questions of being type-safe, or strongly typed, are less important than as in other programming languages, due to the fact that there is no solid definition of a "type". This arises from the fact that any class can be extended at runtime (even base, built-in classes), and instance objects can also be individually extended. This means that, although an object may be of any given class, it may be extended, thus rendering a different type. The definitions of type-safe and 'strongly typed' run contrary to the base philosophy of Ruby, which is that explicit class checking should not be performed (hence lacking variable types in parameter lists); instead, any object which responds to the methods or behaviors a function requires is considered to be sufficient. Features
Ruby currently lacks full support for Unicode, though it has partial support for UTF-8. InteractionThe 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 SyntaxThe 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. When used, the sigil changes the semantics of scope of the variable. The most striking difference from C and Perl is that keywords are typically used to define logical code blocks, without braces (i.e., pair of { and }). For practical purposes there is no distinction between expressions and statements. Line breaks are significant and taken as the end of a statement; a semicolon may be equivalently used. Unlike Python, indentation is not significant. One of the differences of Ruby compared to Python and Perl is that Ruby keeps all of its instance variables completely private to the class and only exposes them through accessor methods (attr_writer, attr_reader, etc). Unlike the "getter" and "setter" methods of other languages like C++ or Java, accessor methods in Ruby can be written with a single line of code. As invocation of these methods does not require the use of parentheses, it is trivial to change an instance variable into a full function, without modifying a single line of code or having to do any refactoring achieving similar functionality to C# and VB.NET property members. Python's property descriptors are similar, but come with a tradeoff in the development process. If one begins in Python by using a publicly exposed instance variable and later changes the implementation to use a private instance variable exposed through a property descriptor, code internal to the class may need to be adjusted to use the private variable rather than the public property. Ruby removes this design decision by forcing all instance variables to be private, but also provides a simple way to declare set and get methods. This is in keeping with the idea that in Ruby, one never directly accesses the internal members of a class from outside of it. Rather one passes a message to the class and receives a response. "Gotchas"Language comparisonSome features which differ notably from languages such as C or Perl:
Some features which differ notably from other languages:
Language features
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. ExamplesThe following examples can be run in a Ruby shell such as Interactive Ruby Shell or saved in a file and run from the command line by typing ruby <filename>. Classic Hello world example: puts "Hello World!" Some basic Ruby code: # Everything, including a literal, is an object, so this works: Conversions: puts 'What\'s your favorite number?' StringsThere 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" The below conventions are equivalent for single quoted strings: a = 'This is a single quoted string' CollectionsConstructing and using an array: a = [1, 'hi', 3.14, 1, 2, [4, 5]] Constructing and using a hash: hash = { :water => 'wet', :fire => 'hot' } Blocks and iteratorsThe two syntaxes for creating a code block: { puts "Hello, World!" } # Note the { braces } Parameter-passing a block to be a closure: # In an object instance variable (denoted with '@'), remember a block. Returning closures from a method: def create_set_and_get(initial_value=0) # Note the default value of 0 Yielding the flow of program control to a block which was provided at calling time:
Iterating over enumerations and arrays using blocks: array = [1, 'hi', 3.14] 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) {|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". Using an enumeration and a block to square the numbers 1 to 10: (1..10).collect {|x| x*x} # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ClassesThe 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 The above prints three names in reverse age order: Bob (33) ExceptionsAn 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 Exceptions are handled by the rescue clause. Such a clause can catch exceptions which inherit from StandardError: begin It is a common mistake to attempt to catch all exceptions with a simple rescue clause. To catch all exceptions one must write: begin Or catch particular exceptions: begin It is also possible to specify that the exception object be made available to the handler clause: begin Alternatively, the most recent exception is stored in the magic global $!. You can also catch several exceptions: begin Or catch an array of exceptions: array_of_exceptions = [RuntimeError, Timeout::Error] ImplementationsRuby 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. There are other less known implementations such as IronRuby (pre-alpha sources available on August 31st, 2007), Rubinius, Ruby.NET, XRuby and YARV. 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 (because this is a complex framework to implement, and it uses a lot of Ruby-specific features). The point when a particular implementation achieves this goal is called The Rails singularity. As of May 2008, only the reference implementation (MRI) and JRuby are able to run Rails unmodified in a production environment. IronRuby and Rubinius start to be able to run Rails test cases, but they still are far from production ready for this task. As of Ruby MRI, Ruby is available on a lot of operating systems such as Linux, Mac OS X, Microsoft Windows, Windows CE and most flavors of Unix. CriticismA number of the design choices made for Ruby have well-known disadvantages:
Ruby 2.0 aims to address all of the aforementioned problems:
Some problems which may not be solved in version 2.0 include:
Repositories and librariesThe Ruby Application Archive (RAA), as well as RubyForge, 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 or Python community, there are a wide range of tools and utilities which serve to foster further development in the language. 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. |
|||||||||||





