Home > Articles > Programming > Ruby

Like this article? We recommend

Like this article? We recommend

Brief Summary of Ruby Language

Methods

Every procedure in Ruby is a method of some object. Some method calls appear to be function calls as in other languages, but in fact they are actually invocations of methods belonging to self. Parentheses can be omitted if unambiguous.

  "string".size()              # call method of "string"
  "string".size                # parentheses can be omitted.

  print "hello world\n"        # call `print' of self

As in Smalltalk, in Ruby operators are special forms of method calls. Consider this, for example:

  1 + 1	# invoke + method with argument 1
  ary[0]	# i.e. `ary.[](0)'

  ary[0] = 55 # i.e. `ary.[]=(0,55)'

Unlike in Smalltalk, operators follow usual operator precedence of programming languages, thus:

  1 + 2 * 3 == 1 + (2 * 3)

To define methods, use def statements.

  def foo(arg1, arg2)
    print arg1, arg2, "\n"
  end

A def statement at the top level defines a global method that can be used just like a function. Usual methods can be defined by def statements within class definition statements.

  class Foo
    def foo
      print "foo method in Foo class\n"
    end
  end

Blocks

Blocks in Ruby are something in between CLU's iterators and Smalltalk's blocks. Like CLU's iterator, a block is a special syntax to pass extra procedural information to the method. For example:

  10.times do |i|
    print i, "\n"
  end

Here, 10.times is a method invocation, with a block starting from "do" to "end." The times method of Integer class evaluates a block 10 times with incremental values from zero. Values given to the block are assigned to the variable surrounded by || for each iteration.

In this code, do .. end can be replaced by ....

As in Smalltalk, blocks are used not only for loop abstraction, but also for conditionals, callbacks, and so on:

  [1,2,3].collect{|x| x*2}     # => [2,4,6]
  [1,2,3].delete_if{|x| x == 1}       # => [2,3]
  [1,2,3].sort{|a,b| b<=>a}    # => [3,2,1]
  "abc".sub(/[ac]/){|x|x.upcase}# => "AbC"

Blocks in Ruby are not first-class objects; rather, you can objectify them explicitly. Objectified blocks are sometimes are called closures because they wrap code blocks along with local variable bindings:

  c = lambda{|x| x + 2}               # objectify block, returns closure
  c.call(5)                    # => 7, evaluate closure

The word lambda is traditionally used in the Lisp world for the function to make closure. Ruby provides the plain alias proc, too.

No Declarations

A variable in Ruby programs can be distinguished by the prefix of its name. Unlike in Perl, the prefix denotes the scope of the variable. It removes declarations from Ruby to let you code less. In addition, by knowing variable scope at a glance enhances readability.

Scope

Prefix

Example

global variable

$

$global

instance variable

@

@instance

local variable

lowercase or _ local

 

constant

uppercase

Constant

class variable

@@

@@class_var (since 1.5.3)

Local variable scope can be introduced by the following statement: class, module, def, and blocks. Scopes introduced by class, module, and def do not nest. But from blocks, local variables in the outer scope can be accessed. Local variables in Ruby follow lexical scoping.

Literals

Ruby provides a variety of literal notations for maximum flexibility—especially for strings. For example:

  "string with escape\n"
  'without escape\n'
  `echo command output pseudo string`
  %q!perl style single quote!
  %Q!perl style double quote\n!
  %w(word list)
  /regular expression/
  %r!another regex form!
 
  <
    

Literals in Ruby are very similar to those in Perl, except that some require % at the front.

Inheritance and Mix-in

Object-oriented features in Ruby were also carefully designed. Ruby supports single inheritance only, which I consider to be a feature. With single inheritance, class hierarchy forms a comprehensive tree, unlike complex network with multiple inheritance. Instead of multiple inheritance, Ruby supports mix-in, the capability to add a set of attributes (methods, constants, and so on) to a class. This set of attributes is called a module. A module is a special kind of class that does not have an explicit superclass, that cannot be instantiated, and that can be mixed into other classes or modules.

An arbitrary class hierarchy formed by multiple inheritance can be reformed using single inheritance and mix-in:

Figure 1: Multiple Inheritance

Figure 2: Single Inheritance

The mix-in class hierarchy is defined as follows in Ruby:

  class Stream
    # defines basic Stream features...
  end
 
  module Readable
    # defines Readable Stream features...
  end
 
  module Writable
    # defines Writable Stream features...
  end
 
  class ReadStream
    

You may feel that this is more restrictive than multiple inheritance, but I believe that you will see how comprehensive the mix-in hierarchy is after you understand it. This method simplifies the class hierarchy extensively.

Individual Methods and Prototype-Based Programming

Although Ruby is classified as a class-based object-oriented language, it allows you to define methods for individual objects.

  foo = Object.new     # create an Object
  def foo.method1      # add a method to it
    print "method1\n"
  end
  foo.method1          # prints "method1\n"

In addition, it allows prototype-based object-oriented programming:

  bar = foo.clone      # make new object after prototype
  bar.method1          # `clone' copies individual method too
  def bar.method2      # new method added
    print "method2\n"
  end
  bar.method2          # prints "method2\n"

Although prototype-based programming is just a theoretical possibility in Ruby, individual methods can be used, such as for an event handler. For example:

  require "gtk"
  window = Gtk::Window::new(Gtk::WINDOW_TOPLEVEL)
  button = Gtk::Button::new("hello")
  window.add(button)
  def button.clicked   # event handler by individual method
    print "hello\n"
    exit
  end
  button.show
  window.show
 
  Gtk::main()

Exceptions

As a modern language, Ruby supports exceptions. All methods in the class library raise exceptions for unusual status. Ruby allows the programmer to omit most error detecting code, and it frees the programmer from worrying about execution under unsatisfied preconditions.

Exceptions are raised by the raise method:

  raise                   # raise unnamed RuntimeError exception
  raise "error!"          # raise RuntimeError with message "error!"
  raise IOError, "closed" # raise IOError with message "closed"

Exceptions are caught by the rescue clause of the begin statement.

  begin
    codeA
  rescue SomeError, AnotherError
    codeB
  end

If codeA raises an exception, which is a subclass of either SomeError or AnotherError, the exception is caught and codeB is executed. All exceptions are subclasses of the Exception class.

Exceptions require you to code—and worry—less less. This is more evidence that Ruby follows the principle of conciseness.

Threads

Ruby supports user-level threading. It's implemented by using setjump()/longjmp() and stack copying. It is not efficient and cannot utilize multiple CPUs. It is also several percents slower than sequential execution. However, it works on all platforms, including MS-DOS machines. Because Ruby behaves uniformly on all platforms, programmers need not worry about threading compatibility. Threading often improves programs' response time by making heavy procedures run in the background.

To start a new thread, you simply call Thread::new with a block:

  Thread::new do
    # code to executed in a thread
  end

To synchronize between threads, the standard class library provides classes such as Mutex and Queue.

Garbage Collection

The reference counting technique used by Python does not recycle circular references, so programmers in this language must cut circular references explicitly later. Ruby uses a conservative mark-and-sweep method of garbage collection, which frees programmers from worrying about circular references. The references are reclaimed automatically by the collector.

The garbage collector scans C stack and registers as well, so that C/C++ written extensions do not have to maintain refcounts or protect local variables. This makes extension development easier than it is for other languages. There is no INCREF/DECREF and no mortal.

The Class Library

Ruby's class library makes this language usable and strong.

This next figure is the digest from Ruby's built-in class library.

Figure 3: The Ruby Built-in Class Library

The inheritance hierarchy is shallow compared to that of Smalltalk. This is partly because implementation sharing is done by mix-in.

Basic data structure classes, such as Array, Hash, IO, String, and Regexp, are designed after Perl. That is, they are designed by reorganizing Perl functions cleanly and consistently into classes. Time, Range, and Numeric classes go beyond simple reorganization. For example, Ruby supports arbitrarily sized integer arithmetic.

Aside from the built-in class library, many add-on libraries exist. They are still small in number compared to CPAN, but they are growing rapidly. Here's the digest from the list of add-on libraries:

  • Matrix

  • Rational Number

  • Design Patterns (Singleton, Proxy)

  • Unicode manipulation

  • CGI

  • Socket

  • HTTP

  • POP3

  • FTP

  • SMTP

  • GUI (Tk, Gtk, and so on)

  • Database (PostgreSQL, Interbase, Oracle, MySQL, and so on)

The list goes on.

Performance

Typical Ruby programs tend to be smaller and faster than their Python equivalents, and almost the same size and a little bit slower than their Perl equivalents. Every operation in Ruby—even integer addition—is done by invoking methods, so the cost to search and invoke methods cannot be ignored, especially for simple programs. When programs get bigger and more complex, however, no significant performance difference should arise as a result of methods.

The following is the outcome of a simple longest-word search program over /usr/share/dict/words (409067 bytes). These were tested on my Pentium-200MHz Linux machine.

Program

Lines

Seconds

Ruby

14

1.046

Perl

15

0.593

Python

16

5.001

As stated before, Ruby is a bit slower than Perl because of the overhead for method searching; however, it's much faster than Python.

Benchmark programs:

Ruby:

  ---
  #!/usr/bin/ruby
 
  len = 0
  words = []
  while line = gets()
    if line.size == len
      words.push line
    elsif line.size > len
      words = [line]
      len = line.size
    end
  end
  for word in words
    print word
  end
  ---
 

Perl:

  ---
  #!/usr/bin/perl
 
  $len = 0;
  @words = ();
 
  while (<>) {
      if (length($_) == $len) {
          push(@words, $_);
      }
      elsif (length($_) > $len) {
          @words = ($_);
          $len = length($_);
      }
  }
  for $word (@words) {
      print $word;
  }
  ---
 

Python:

  ---
  #!/usr/bin/python
 
  import sys
 
  size = 0
  words = []
 
  for f in sys.argv[1:]:
    io = open(f)
    while 1:
      line = io.readline()
      if line == "": break
      if len(line) == size:
        words.append(line)
      elif len(line) > size:
        words = [line]
        size = len(line)
  for word in words:
    print word,
  ---

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020