<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Ddilipd</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Ddilipd"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Ddilipd"/>
	<updated>2026-05-09T10:56:13Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54241</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54241"/>
		<updated>2011-10-28T23:44:06Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Blocks */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism).Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}   #define lambda proc&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a                 #call proc object&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
block = lambda { |x| &amp;quot;Hello #{x}!&amp;quot; }  &lt;br /&gt;
puts block.call 'World'&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
Hello World!&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Above code shows example of passing arguments using lambda.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ Proc and Lamda]&amp;lt;/ref&amp;gt; takes in a block and returns a Proc object which will run the code in the block when call method is invoked. In Proc.new created proc the return control is from the method enclosing the Proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method.In a lambda created proc, the return statement returns only from the proc itself. This is the difference from the Proc.new created proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  class ParkingLot                  &lt;br /&gt;
    def initialize(n)&lt;br /&gt;
      @spotsAvailable = n                     #initialize the variable&lt;br /&gt;
    end&lt;br /&gt;
    def park                                      &lt;br /&gt;
      puts &amp;quot;Park your car&amp;quot;&lt;br /&gt;
      @spotsAvailable = @spotsAvailable - 1   #decrement the number of available slots&lt;br /&gt;
    end&lt;br /&gt;
    def unpark&lt;br /&gt;
      puts &amp;quot;Unpark your car&amp;quot;&lt;br /&gt;
      @spotsAvailable = @spotsAvailable + 1   #increment the available slots&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. There is another example of class ParkingLot which has two methods defined, park and unpark. It maintains the number of available spots in the ParkingLot. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor&amp;lt;ref&amp;gt;[http://www.rubyist.net/~slagell/ruby/accessors.html Accessors]&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of [http://download.oracle.com/javase/tutorial/java/IandI/abstract.html abstract methods]. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/duck_typing.html Duck Typing]&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm Ruby Classes]&lt;br /&gt;
*[http://rubysource.com/ruby-mixins-2/ Ruby Inheritance]&lt;br /&gt;
*[http://pragdave.blogs.pragprog.com/pragdave/2008/09/fun-with-procs.html Ruby Procs]&lt;br /&gt;
*[http://moonbase.rydia.net/mental/blog/programming/currying-in-ruby Currying]&lt;br /&gt;
*[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ Procs, Blocks and Lambdas]&lt;br /&gt;
*[http://moonmaster9000.tumblr.com/post/477872071/class-variables-and-inheritance-in-ruby Class variables and Inheritance]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/047-issue-15-duck-typing-2.html Best Practices]&lt;br /&gt;
*[http://rubysource.com/making-ruby-quack%E2%80%94why-we-love-duck-typing/ Duck Typing]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;br /&gt;
* Design Java by Dale Skrien&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54237</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54237"/>
		<updated>2011-10-28T23:18:00Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Procs And Lambdasproc and Lamda */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism).Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}   #define lambda proc&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a                 #call proc object&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt; takes in a block and returns a Proc object which will run the code in the block when call method is invoked. In Proc.new created proc the return control is from the method enclosing the Proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method.In a lambda created proc, the return statement returns only from the proc itself. This is the difference from the Proc.new created proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor&amp;lt;ref&amp;gt;[http://www.rubyist.net/~slagell/ruby/accessors.html Accessors]&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of [http://download.oracle.com/javase/tutorial/java/IandI/abstract.html abstract methods]. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/duck_typing.html Duck Typing]&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm Ruby Classes]&lt;br /&gt;
*[http://rubysource.com/ruby-mixins-2/ Ruby Inheritance]&lt;br /&gt;
*[http://pragdave.blogs.pragprog.com/pragdave/2008/09/fun-with-procs.html Ruby Procs]&lt;br /&gt;
*[http://moonbase.rydia.net/mental/blog/programming/currying-in-ruby Currying]&lt;br /&gt;
*[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ Procs, Blocks and Lambdas]&lt;br /&gt;
*[http://moonmaster9000.tumblr.com/post/477872071/class-variables-and-inheritance-in-ruby Class variables and Inheritance]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/047-issue-15-duck-typing-2.html Best Practices]&lt;br /&gt;
*[http://rubysource.com/making-ruby-quack%E2%80%94why-we-love-duck-typing/ Duck Typing]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;br /&gt;
* Design Java by Dale Skrien&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54236</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54236"/>
		<updated>2011-10-28T23:17:06Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Blocks */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism).Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}   #define lambda proc&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a                 #call proc object&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked. In Proc.new created proc the return control is from the method enclosing the Proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method.In a lambda created proc, the return statement returns only from the proc itself. This is the difference from the Proc.new created proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor&amp;lt;ref&amp;gt;[http://www.rubyist.net/~slagell/ruby/accessors.html Accessors]&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of [http://download.oracle.com/javase/tutorial/java/IandI/abstract.html abstract methods]. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/duck_typing.html Duck Typing]&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm Ruby Classes]&lt;br /&gt;
*[http://rubysource.com/ruby-mixins-2/ Ruby Inheritance]&lt;br /&gt;
*[http://pragdave.blogs.pragprog.com/pragdave/2008/09/fun-with-procs.html Ruby Procs]&lt;br /&gt;
*[http://moonbase.rydia.net/mental/blog/programming/currying-in-ruby Currying]&lt;br /&gt;
*[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ Procs, Blocks and Lambdas]&lt;br /&gt;
*[http://moonmaster9000.tumblr.com/post/477872071/class-variables-and-inheritance-in-ruby Class variables and Inheritance]&lt;br /&gt;
*[http://blog.rubybestpractices.com/posts/gregory/047-issue-15-duck-typing-2.html Best Practices]&lt;br /&gt;
*[http://rubysource.com/making-ruby-quack%E2%80%94why-we-love-duck-typing/ Duck Typing]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;br /&gt;
* Design Java by Dale Skrien&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54229</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54229"/>
		<updated>2011-10-28T22:16:47Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Lambda method */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism).Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked. In Proc.new created proc the return control is from the method enclosing the Proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method.In a lambda created proc, the return statement returns only from the proc itself. This is the difference from the Proc.new created proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/duck_typing.html Duck Typing]&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm dsfsfd]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54228</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54228"/>
		<updated>2011-10-28T22:16:35Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Lambda method */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism).Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked. In Proc.new created proc the return control is from the method enclosing the Proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method.In a lambda created proc, the return statement returns only from the proc itself. This is the difference from the Proc.new created Proc&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/duck_typing.html Duck Typing]&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm dsfsfd]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54227</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54227"/>
		<updated>2011-10-28T22:15:33Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Proc.new */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism).Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked. In Proc.new created proc the return control is from the method enclosing the Proc.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/duck_typing.html Duck Typing]&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm dsfsfd]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54226</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54226"/>
		<updated>2011-10-28T21:50:43Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism).Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[http://rubylearning.com/satishtalim/duck_typing.html Duck Typing]&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm dsfsfd]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54222</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54222"/>
		<updated>2011-10-28T20:36:44Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* External links */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[[8] http://rubylearning.com/satishtalim/duck_typing.html&amp;gt;&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates &amp;gt;ref&amp;gt;[http://en.wikipedia.org/wiki/Duck_typing Duck typing]&amp;lt;/ref&amp;gt; in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm dsfsfd]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54220</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54220"/>
		<updated>2011-10-28T20:34:50Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Further reading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[[8] http://rubylearning.com/satishtalim/duck_typing.html&amp;gt;&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]&amp;lt;/ref&amp;gt; in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54219</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54219"/>
		<updated>2011-10-28T20:34:24Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* External links */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing&amp;lt;ref&amp;gt;[[8] http://rubylearning.com/satishtalim/duck_typing.html&amp;gt;&amp;lt;/ref&amp;gt;. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing]&amp;lt;/ref&amp;gt; in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.tutorialspoint.com/ruby/ruby_classes.htm]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005), ISBN 1-932394-18-4&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54216</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54216"/>
		<updated>2011-10-28T20:31:17Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Currying */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, by fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing] in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.cs.indiana.edu/~jsobel/rop.html An Introduction to Reflection-Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005), ISBN 1-932394-18-4&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54215</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54215"/>
		<updated>2011-10-28T20:30:33Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Currying */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function curried_add &lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class&amp;lt;ref&amp;gt;[http://phrogz.net/programmingruby/tut_classes.html Ruby Classes]&amp;lt;/ref&amp;gt; methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing] in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.cs.indiana.edu/~jsobel/rop.html An Introduction to Reflection-Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005), ISBN 1-932394-18-4&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54213</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54213"/>
		<updated>2011-10-28T20:30:10Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Currying */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures &amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ Closures]&amp;lt;/ref&amp;gt;help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas&amp;lt;ref&amp;gt;[http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/ proc and Lamda]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for the addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]                        #original addition function add&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry              #curried function&lt;br /&gt;
add_to_ten = curried_add[10]         #only 1 number specified to curried function curried_add, fixing one of the input values&lt;br /&gt;
add_to_twenty = curried_add[20]      #thus the curried function always adds 10 and 20 to the second number when we use it with&lt;br /&gt;
                                     #add_to_ten  and add_to_twenty respectively&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]                   #adding second number 5 to the fixed value of 10&lt;br /&gt;
puts add_to_twenty[5]                #adding second number 5 to the fixed value of 20&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock                   #BookInStock is a class name&lt;br /&gt;
    def initialize(isbn, price)       #initialize is used to initialize instance variables&lt;br /&gt;
       @isbn = isbn                   #@isbn and @price are instance variables&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book                     #self denotes class method&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title       #getter method&lt;br /&gt;
    attr_writer :price       #setter method&lt;br /&gt;
    attr_accessor : isbn     #getter and setter methods &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) #raise indicates exception&lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing] in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.cs.indiana.edu/~jsobel/rop.html An Introduction to Reflection-Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005), ISBN 1-932394-18-4&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54207</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=54207"/>
		<updated>2011-10-28T20:19:48Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
       @isbn = isbn&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing] in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External links=&lt;br /&gt;
*[http://www.cs.indiana.edu/~jsobel/rop.html An Introduction to Reflection-Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
=Further reading=&lt;br /&gt;
* Ira R. Forman and Nate Forman, ''Java Reflection in Action'' (2005), ISBN 1-932394-18-4&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53651</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53651"/>
		<updated>2011-10-21T01:20:51Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby. Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
       @isbn = isbn&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing] in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;br /&gt;
&lt;br /&gt;
[4] http://phrogz.net/programmingruby/tut_classes.html&lt;br /&gt;
&lt;br /&gt;
[5] http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/&lt;br /&gt;
&lt;br /&gt;
[6] http://www.tutorialspoint.com/ruby/ruby_classes.htm&lt;br /&gt;
&lt;br /&gt;
[7] Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;br /&gt;
&lt;br /&gt;
[8] http://rubylearning.com/satishtalim/duck_typing.html&lt;br /&gt;
&lt;br /&gt;
[9] http://devblog.famundo.com/articles/2007/01/12/ruby-duck-typing-goodness&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53649</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53649"/>
		<updated>2011-10-21T01:20:39Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
       @isbn = isbn&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing] in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;br /&gt;
&lt;br /&gt;
[4] http://phrogz.net/programmingruby/tut_classes.html&lt;br /&gt;
&lt;br /&gt;
[5] http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/&lt;br /&gt;
&lt;br /&gt;
[6] http://www.tutorialspoint.com/ruby/ruby_classes.htm&lt;br /&gt;
&lt;br /&gt;
[7] Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;br /&gt;
&lt;br /&gt;
[8] http://rubylearning.com/satishtalim/duck_typing.html&lt;br /&gt;
&lt;br /&gt;
[9] http://devblog.famundo.com/articles/2007/01/12/ruby-duck-typing-goodness&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53644</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53644"/>
		<updated>2011-10-21T01:19:00Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Attributes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
In the following wiki, we will be covering the basics of closures and currying. We will then go into the details of object-oriented concepts such as data encapsulation, inheritance and polymorphism. The wiki ends by covering the most popular feature in Ruby called duck typing (unbounded polymorphism). &lt;br /&gt;
&lt;br /&gt;
Since the lecture 5 material in the CSC517 covers object-oriented concepts specific to Ruby, thus we have restricted to the same.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide [http://en.wikipedia.org/wiki/Inheritance inheritance], [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism] and [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation], the three pillars. You can have class methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
       @isbn = isbn&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methods provide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates [http://en.wikipedia.org/wiki/Duck_typing Duck typing] in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new) # Frog is an animal&lt;br /&gt;
  t.test_animal(Dinosaur.new) # Dinosaur is an animal&lt;br /&gt;
  t.test_animal(Table.new) # Table is an animal!!&lt;br /&gt;
  t.test_animal(Bird.new) # Bird is not an animal&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing dynamic typing] are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;br /&gt;
&lt;br /&gt;
[4] http://phrogz.net/programmingruby/tut_classes.html&lt;br /&gt;
&lt;br /&gt;
[5] http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/&lt;br /&gt;
&lt;br /&gt;
[6] http://www.tutorialspoint.com/ruby/ruby_classes.htm&lt;br /&gt;
&lt;br /&gt;
[7] Programming Ruby, The Pragmatic Programmer's Guide by Dave Thomas&lt;br /&gt;
&lt;br /&gt;
[8] http://rubylearning.com/satishtalim/duck_typing.html&lt;br /&gt;
&lt;br /&gt;
[9] http://devblog.famundo.com/articles/2007/01/12/ruby-duck-typing-goodness&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53125</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53125"/>
		<updated>2011-10-20T18:18:25Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide inheritance, polymorphism and encapsulation, the three pillars. You can have class methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
       @isbn = isbn&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methodsprovide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. There are three levels of protection provided by Ruby,&lt;br /&gt;
&lt;br /&gt;
1. Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default (   except initialize, which is private).&lt;br /&gt;
2. Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3. Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control. One can just choose any relevant access specifier before each method is defined as shown here.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
       raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
       puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However as mentioned earlier Ruby programmers use abstract methods very rarely.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes which are basic elements in object-oriented programming and duck typing which is very popular in Ruby and used most often. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation, code reuse via inheritance and polymorphism. Ultimately we believe that the developer has to weigh the options available according to the requirements of the application and use the Ruby features accordingly.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53119</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53119"/>
		<updated>2011-10-20T18:07:11Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
A class is the blueprint from which individual objects are created.  In object-oriented programming classes are the basic elements which provide inheritance, polymorphism and encapsulation, the three pillars. You can have class methods and instance methods. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is the example for a class BookInStock. &lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
       @isbn = isbn&lt;br /&gt;
       @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    def self.book&lt;br /&gt;
        puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
Here, initialize is a special method in Ruby. When you call BookInStock.new to create a new BookInStock object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state. This is very similar to constructors in Java. Then there is self.book which is class method which is very similar to static methods in Java. The variables starting with @ are instance variables meaning that they are associated with the instances. In the next few sections we will take a look at the attributes, access control mechanisms and inheritance features provided in the class.&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors. Ruby defines three accessor methods attr_reader, attr_writer and attr_accessor. &lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. &lt;br /&gt;
&lt;br /&gt;
These methodsprovide access to the underlying instance variables of the name (with a leading @sign). The below example illustrates the use of these methods. &lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
These methods will have the same effect as shown in the below table.&lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  #outputs blurp, blurp&lt;br /&gt;
  beverage.intake #outputs Sweet, tasty tasty&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by explaining what closures are and in Ruby how this can be achieved using block and procs. Then we explained classes and duck typing in Ruby. Closures allow a programmer to write shorter code, while classes in Ruby provide data encapsulation and extension of code . Ultimately it is the developer who chooses when to use closures and classes based on the needs of his application.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53112</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53112"/>
		<updated>2011-10-20T17:57:18Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
Classes are templates for creating object instances. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
         @isbn = isbn&lt;br /&gt;
         @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    delf self.book&lt;br /&gt;
       puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors.&lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance&lt;br /&gt;
variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. These methods&lt;br /&gt;
provide access to the underlying instance variables of the name name (with a leading @&lt;br /&gt;
sign).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  &lt;br /&gt;
  beverage.intake&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by listing out the collections present in Java which uses JCF, and C++ which uses STL. Then we made a comparison of the collections in C++ , Java and Ruby. Each language's implementation of collections has its pros and cons. Ultimately it is the developer who chooses which one to use, and this is based on the needs of his application. In general C++ STL provides collections that are fast, Java JCF provides collections that are safe, while in Ruby, the collections can be written with minimal code as they are built into the language.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53111</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53111"/>
		<updated>2011-10-20T17:52:26Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Duck typing (Unbounded Polymorphism) */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
Classes are templates for creating object instances. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
         @isbn = isbn&lt;br /&gt;
         @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    delf self.book&lt;br /&gt;
       puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors.&lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance&lt;br /&gt;
variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. These methods&lt;br /&gt;
provide access to the underlying instance variables of the name name (with a leading @&lt;br /&gt;
sign).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  &lt;br /&gt;
  beverage.intake&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53109</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53109"/>
		<updated>2011-10-20T17:50:41Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Currying */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to one's needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
Classes are templates for creating object instances. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
         @isbn = isbn&lt;br /&gt;
         @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    delf self.book&lt;br /&gt;
       puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors.&lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance&lt;br /&gt;
variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. These methods&lt;br /&gt;
provide access to the underlying instance variables of the name name (with a leading @&lt;br /&gt;
sign).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  &lt;br /&gt;
  beverage.intake&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may prove increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53106</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53106"/>
		<updated>2011-10-20T17:49:46Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Procs And Lambdas */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in [http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby].&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
Classes are templates for creating object instances. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
         @isbn = isbn&lt;br /&gt;
         @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    delf self.book&lt;br /&gt;
       puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors.&lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance&lt;br /&gt;
variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. These methods&lt;br /&gt;
provide access to the underlying instance variables of the name name (with a leading @&lt;br /&gt;
sign).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  &lt;br /&gt;
  beverage.intake&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may prove increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53105</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53105"/>
		<updated>2011-10-20T17:48:38Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Proc method */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
Classes are templates for creating object instances. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
         @isbn = isbn&lt;br /&gt;
         @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    delf self.book&lt;br /&gt;
       puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors.&lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance&lt;br /&gt;
variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. These methods&lt;br /&gt;
provide access to the underlying instance variables of the name name (with a leading @&lt;br /&gt;
sign).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  &lt;br /&gt;
  beverage.intake&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may prove increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53104</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53104"/>
		<updated>2011-10-20T17:47:35Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Proc method */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby] 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
Classes are templates for creating object instances. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
         @isbn = isbn&lt;br /&gt;
         @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    delf self.book&lt;br /&gt;
       puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors.&lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance&lt;br /&gt;
variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. These methods&lt;br /&gt;
provide access to the underlying instance variables of the name name (with a leading @&lt;br /&gt;
sign).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  &lt;br /&gt;
  beverage.intake&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may prove increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53103</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53103"/>
		<updated>2011-10-20T17:46:41Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Proc.new */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
Classes are templates for creating object instances. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
         @isbn = isbn&lt;br /&gt;
         @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    delf self.book&lt;br /&gt;
       puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors.&lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance&lt;br /&gt;
variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. These methods&lt;br /&gt;
provide access to the underlying instance variables of the name name (with a leading @&lt;br /&gt;
sign).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  &lt;br /&gt;
  beverage.intake&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may prove increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53101</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53101"/>
		<updated>2011-10-20T17:45:14Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Closures */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A [http://en.wikipedia.org/wiki/Closure_(computer_science) closure] may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method &amp;lt;nowiki&amp;gt;&amp;lt;nowiki&amp;gt;Insert non-formatted text here&amp;lt;/nowiki&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;nowiki&amp;gt;Insert non-formatted text here&amp;lt;/nowiki&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/nowiki&amp;gt;is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Class==&lt;br /&gt;
Classes are templates for creating object instances. Class methods are methods that are called on a class and instance methods are methods that are called on an instance of a class. Here is a quick example and then we’ll go into a bit more detail.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    def initialize(isbn, price)&lt;br /&gt;
         @isbn = isbn&lt;br /&gt;
         @price = Float(price)&lt;br /&gt;
    end&lt;br /&gt;
    delf self.book&lt;br /&gt;
       puts “Class method”&lt;br /&gt;
    end&lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Attributes===&lt;br /&gt;
An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors.&lt;br /&gt;
&lt;br /&gt;
Attr_reader: Creates instance variables and corresponding methods that return the value of each instance&lt;br /&gt;
variable.&lt;br /&gt;
&lt;br /&gt;
Attr_writer: Creates an accessor method to allow assignment to the attribute&lt;br /&gt;
&lt;br /&gt;
Attr_accessor: Creates a reader and a writer method for each symbol passed as an argument. These methods&lt;br /&gt;
provide access to the underlying instance variables of the name name (with a leading @&lt;br /&gt;
sign).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class BookInStock&lt;br /&gt;
    attr_reader :title&lt;br /&gt;
    attr_writer :price&lt;br /&gt;
    attr_accessor : isbn &lt;br /&gt;
  end &lt;br /&gt;
&lt;br /&gt;
  Shortcut	         Effect&lt;br /&gt;
  attr_reader :title	 def title; @title; end&lt;br /&gt;
  attr_writer :price	 def price=(price); @price=price; end&lt;br /&gt;
  attr_accessor :isbn	 attr_reader :isbn; attr_writer :isbn&lt;br /&gt;
&lt;br /&gt;
===Inheritance===&lt;br /&gt;
&lt;br /&gt;
Inheritance is one of the pillars of object-oriented programming. Inheritance allows you to create a class that is a refinement or specialization of another class. This class is called a subclass of the original, and the original is a superclass of the subclass. &lt;br /&gt;
&lt;br /&gt;
For example here Ale is-a subclass of Beer and Beer is-a superclass of Ale. Inheritance allows a subclass to have all the methods defined in the superclass and hence promotes code reuse.  In addition subclass can override the methods which are much more specialized than superclass.  Ale class now gets the intake method defined in the Beer and also it has another method defined taste which varies from one subclass to another. Also it’s important to note that all classes in Ruby inherit from the Object class and hence all the methods declared in the Object class are now implicitly part of any class we declare.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Beer  &lt;br /&gt;
    def intake  &lt;br /&gt;
      puts &amp;quot;blurp blurp&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  class Ale &amp;lt; Beer  &lt;br /&gt;
    def taste &lt;br /&gt;
      puts &amp;quot;Sweet, tasty tasty&amp;quot;  &lt;br /&gt;
    end  &lt;br /&gt;
  end  &lt;br /&gt;
 &lt;br /&gt;
  beverage = Ale.new  &lt;br /&gt;
  beverage.taste  &lt;br /&gt;
  beverage.intake&lt;br /&gt;
&lt;br /&gt;
===Access control===&lt;br /&gt;
&lt;br /&gt;
Ruby allows having control over the methods defined in the class. &lt;br /&gt;
&lt;br /&gt;
There are three levels of protection provided by Ruby:&lt;br /&gt;
&lt;br /&gt;
1.	Public methods can be called by any class. No access control is enforced. In Ruby, methods are public by default ( except initialize, which is private).&lt;br /&gt;
2.	Protected methods can be used by the class which defines them and the subclass which inherit these classes.&lt;br /&gt;
3.	Private methods can be called only in the context of the current object. You can’t invoke other objects private methods. &lt;br /&gt;
&lt;br /&gt;
The below example shows some details about access control.&lt;br /&gt;
  class AccessControlExample&lt;br /&gt;
   def method1 # default is “public” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   protected # subsequent methods will be “protected” &lt;br /&gt;
   def method2 # will be “protected” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
   private # subsequent methods will be “private” &lt;br /&gt;
   def method3 # will be “private” &lt;br /&gt;
     #... &lt;br /&gt;
   end &lt;br /&gt;
   public # subsequent methods will be “public” &lt;br /&gt;
   def method4 # and this will be “public” &lt;br /&gt;
    #... &lt;br /&gt;
   end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===Abstract methods===&lt;br /&gt;
&lt;br /&gt;
Ruby doesn’t support the concept of abstract methods. This is because Ruby is dynamically typed and you can add methods on the fly. If you want to simulate the notion of abstract method, you can do the following,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Animal&lt;br /&gt;
    def talk	&lt;br /&gt;
           raise “NotImplementedError.new(&amp;quot;Method not implemented&amp;quot;) &lt;br /&gt;
    end &lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur &amp;lt; Animal&lt;br /&gt;
    def talk&lt;br /&gt;
           puts “Roar! Roar”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
Here Dinosaur class implements talk method. If you don’t implement the talk method in Dinosaur, an attempt to instantiate the class throws an error. However the notion of abstract methods in the Ruby are not used heavily.&lt;br /&gt;
&lt;br /&gt;
==Duck typing (Unbounded Polymorphism)==&lt;br /&gt;
&lt;br /&gt;
In Ruby, the class is never the type. Instead, the type of an object is defined more by what that object can do which is determined by the methods and properties rather than inheritance from particular class. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck. &lt;br /&gt;
&lt;br /&gt;
Lets look at the example below. &lt;br /&gt;
&lt;br /&gt;
There are 4 classes defined which are not related in any way. The classes Frog, Dinosaur, Table have a talk method defined while the class Bird has chirp method defined. Since the Table class has a talk method we can say it has animal even though by reality it does not belong which illustrates Duck typing in Ruby. Since Bird class does not implement the talk method it is not classified as of type animal. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  class Frog&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;ribbit, ribbit&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Dinosaur&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;Roar&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Table&lt;br /&gt;
    def talk&lt;br /&gt;
         puts &amp;quot;chss, chss&amp;quot;&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Bird&lt;br /&gt;
    def chirp&lt;br /&gt;
      puts “kuckoo”&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Test&lt;br /&gt;
    def test_animal(an)&lt;br /&gt;
         an.talk&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  t = Test.new&lt;br /&gt;
  t.test_animal(Frog.new)&lt;br /&gt;
  t.test_animal(Dinosaur.new)&lt;br /&gt;
  t.test_animal(Table.new)&lt;br /&gt;
  t.test_animal(Bird.new)&lt;br /&gt;
&lt;br /&gt;
The downside of duck typing is that, the absence of the static type checking may prove increase the execution time. This is also dynamic typing because type information is determined at run-time. Other well-known languages which heavily use dynamic typing are Python, PHP, Perl, Objective-C, etc.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53089</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=53089"/>
		<updated>2011-10-20T17:26:25Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A closure may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method &amp;lt;nowiki&amp;gt;&amp;lt;nowiki&amp;gt;Insert non-formatted text here&amp;lt;/nowiki&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;nowiki&amp;gt;Insert non-formatted text here&amp;lt;/nowiki&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/nowiki&amp;gt;is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://en.wikipedia.org/wiki/Closure_(computer_science)&lt;br /&gt;
&lt;br /&gt;
[2] http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/&lt;br /&gt;
&lt;br /&gt;
[3] http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52993</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52993"/>
		<updated>2011-10-20T12:44:50Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A closure may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call method &amp;lt;nowiki&amp;gt;&amp;lt;nowiki&amp;gt;Insert non-formatted text here&amp;lt;/nowiki&amp;gt;&amp;lt;nowiki&amp;gt;&amp;lt;nowiki&amp;gt;Insert non-formatted text here&amp;lt;/nowiki&amp;gt;&amp;lt;/nowiki&amp;gt;&amp;lt;/nowiki&amp;gt;is invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is the concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52992</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52992"/>
		<updated>2011-10-20T12:42:23Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A closure may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call methodis invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52991</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52991"/>
		<updated>2011-10-20T12:40:32Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A closure may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call methodis invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52990</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52990"/>
		<updated>2011-10-20T12:39:43Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. This means it can access the lexical environment of its definition. A closure may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call methodis invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52989</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52989"/>
		<updated>2011-10-20T12:38:48Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of closures and blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. It can access the lexical environment of its definition. A closure may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call methodis invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52988</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52988"/>
		<updated>2011-10-20T12:38:00Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of Closures, blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. It can access the lexical environment of its definition. A closure may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code. Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
===Blocks===&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
{ puts &amp;quot;Hello World&amp;quot; }                # braces block&lt;br /&gt;
&lt;br /&gt;
do&lt;br /&gt;
{ puts &amp;quot;Hello World 1&amp;quot; }              # do/end block&lt;br /&gt;
{ puts &amp;quot;Hello World 2&amp;quot; }&lt;br /&gt;
{ puts &amp;quot;Hello World 3&amp;quot; }&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Blocks can be instantiated as a Proc object using the Proc or lambda method. The block is then bound to a set of local variables. Once bound, the block code may be called in different contexts through these set variables.Using the example mentioned in lecture 5 in class.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
# Class to generate adders&lt;br /&gt;
class AdderGen&lt;br /&gt;
  def initialize(n)&lt;br /&gt;
	@block = lambda {|a| n + a}&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def add(a)&lt;br /&gt;
	@block.call a&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
twoAdder = AdderGen.new 2&lt;br /&gt;
incrementer = AdderGen.new 1&lt;br /&gt;
puts incrementer.add(4)&lt;br /&gt;
puts twoAdder.add(6)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
5&lt;br /&gt;
8&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
@block is the Ruby closure that gets initialized when the lambda method gets called through the class initialize method. The block remembers the parameter with which the initialize method was called even after the initialize method exits. This value of the block  is used during the add method invocation.&lt;br /&gt;
&lt;br /&gt;
===Procs And Lambdas===&lt;br /&gt;
There are three ways to create a Proc object in Ruby.&lt;br /&gt;
&lt;br /&gt;
====Proc.new====&lt;br /&gt;
Proc.new takes in a block and returns a Proc object which will run the code in the block when call methodis invoked.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = Proc.new {puts &amp;quot;Create Proc.new object&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Proc method====&lt;br /&gt;
The proc method is equivalent to Proc.new in Ruby 1.9, but in Ruby 1.8 it is equivalent to lambda. &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = proc {puts &amp;quot;Create proc from Proc method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Lambda method====&lt;br /&gt;
This creates a  proc object using the lambda method&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
proc_object = lambda {puts &amp;quot;Create proc from Lambda method&amp;quot;}&lt;br /&gt;
proc_object.call&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Currying==&lt;br /&gt;
Currying is concept of creating a new function out of an existing function by fixing the value of some of its input parameters.  Currying thus makes a generic function more specific to ones needs. Consider the following example where we have a Proc for addition of two numbers. Using currying we can fix the value of the first argument so that when the curried function is called later on with only one argument, it can use the earlier fixed value as the other argument for its addition. Ruby 1.9 allows the creation of a curry-able proc by calling the curry method on it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
add = lambda {|a,b| a + b}&lt;br /&gt;
puts add[1,2]&lt;br /&gt;
&lt;br /&gt;
curried_add = add.curry&lt;br /&gt;
add_to_ten = curried_add[10]&lt;br /&gt;
add_to_twenty = curried_add[20]&lt;br /&gt;
&lt;br /&gt;
puts add_to_ten[5]&lt;br /&gt;
puts add_to_twenty[5]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Output&lt;br /&gt;
3&lt;br /&gt;
15&lt;br /&gt;
25&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52987</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52987"/>
		<updated>2011-10-20T12:31:30Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of Closures, blocks, currying and OOP in Ruby.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
A closure is a block of code that “closes over”. It can access the lexical environment of its definition. A closure may be defined in one scope and get called outside this scope. Thus a closure  retains the values of all the variables that were in scope when the closure was defined. Closures help in making the code short such that one can do more with less code.&lt;br /&gt;
&lt;br /&gt;
===Closure in Ruby===&lt;br /&gt;
Ruby supports closures through Blocks and Procs.&lt;br /&gt;
&lt;br /&gt;
====Blocks====&lt;br /&gt;
A block is a set of Ruby statements either between braces or a do/end pair, and appear only immediately after a method invocation. Ruby uses the following standard - braces for single-line blocks and do/end for multiline blocks.&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52986</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52986"/>
		<updated>2011-10-20T12:27:46Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of Closures, blocks, currying and OOP in Ruby.&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52985</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52985"/>
		<updated>2011-10-20T12:27:33Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki textbook chapter on OOLS Lecture 5. Covers the basic of Closures, blocks, currying and OOP in Ruby&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011&amp;diff=52845</id>
		<title>CSC/ECE 517 Fall 2011</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011&amp;diff=52845"/>
		<updated>2011-10-20T02:19:22Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[[Link title]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a ms]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a cs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a ri]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a lj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1b sa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1b ds]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1b tj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1c cm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1c sj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1c ka]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1d sr]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e vs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e aa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1a sc]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e dm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e an]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e sa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e lm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1g vn]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1f rs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1f sv]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1g jn]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1h ps]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1e sm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1i zf]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1g rn]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1i cl]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1d ss]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1i lj]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1h hs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 1d gs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2b ns]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2b jp]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2a av]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2f jm]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2e ad]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2e kt]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2e gp]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2b qu]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2c bs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2c rs]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2a ca]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch1 2b rv]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2c ds]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2b sa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2f vh]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch2 2e ps]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 3a oe]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 3h rr]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 3h ss]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 4b js]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch3 4b ms]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4b ds]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4i aa]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4i sd]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4d mt]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4d ls]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4d ch]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4c ap]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4h sv]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4e cl]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4a ga]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4f sl]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4i js]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4f ss]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2011/ch4 4c dm]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*[[trial]]&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52839</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4b_ds&amp;diff=52839"/>
		<updated>2011-10-20T02:15:51Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: Created page with &amp;quot;dilip&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;dilip&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51136</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51136"/>
		<updated>2011-09-26T02:44:28Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Extension capability===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the case in java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  map&amp;lt;char,int&amp;gt; mymap;&lt;br /&gt;
  map&amp;lt;char,int&amp;gt;::iterator it;&lt;br /&gt;
  int count = 0;&lt;br /&gt;
  // insert some values:&lt;br /&gt;
  mymap['a']=10;&lt;br /&gt;
  mymap['b']=20;&lt;br /&gt;
  mymap['c']=30;&lt;br /&gt;
  mymap['d']=40;&lt;br /&gt;
  mymap['e']=50;&lt;br /&gt;
  mymap['f']=60;&lt;br /&gt;
&lt;br /&gt;
  //suppose you decide to delete the 3rd item onwards&lt;br /&gt;
  for ( it=mymap.begin() ; it != mymap.end(); it++ ){&lt;br /&gt;
    if(count &amp;gt;=2){&lt;br /&gt;
       mymap.erase(it); // This statement is dangerous. When the iterator is used to delete the entry the reference that the iterator holds                                     &lt;br /&gt;
                        // is lost. Now we have lost the reference to our position in the map.&lt;br /&gt;
                        // Intuitively it seems iterator just specifies the entry in the map that has to be deleted. But the iterator is a &lt;br /&gt;
                        // pointer that holds a reference and it would jump to the beginning of the map.&lt;br /&gt;
    }&lt;br /&gt;
    count++&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java this can cause problems if the programmer is not careful.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Consider the following piece of code&lt;br /&gt;
&lt;br /&gt;
HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt; outer = new HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt;();&lt;br /&gt;
HashMap&amp;lt;String,String&amp;gt; inner = new HashMap&amp;lt;String,String&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;A&amp;quot;,&amp;quot;1&amp;quot;);&lt;br /&gt;
outer.add(&amp;quot;A1&amp;quot;,inner);&lt;br /&gt;
&lt;br /&gt;
inner.clear(); // This statement also erases the entry in the outer HashMap. This is because of the fact mentioned above.&lt;br /&gt;
               // When the inner hash map is added as an entry into the outer HashMap only a reference gets stored and not the actual HashMap          &lt;br /&gt;
               // Object.This is not the case with C++ STL which has copy semantics&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;B&amp;quot;,&amp;quot;2&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by listing out the collections present in Java which uses JCF, and C++ which uses STL. Then we made a comparison of the collections in C++ , Java and Ruby. Each language's implementation of collections has its pros and cons. Ultimately it is the developer who chooses which one to use, and this is based on the needs of his application. In general C++ STL provides collections that are fast, Java JCF provides collections that are safe, while in Ruby, the collections can be written with minimal code as they are built into the language.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51118</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51118"/>
		<updated>2011-09-26T02:26:13Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Manipulation of container objects using Iterators */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Extension capability===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the case in java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  map&amp;lt;char,int&amp;gt; mymap;&lt;br /&gt;
  map&amp;lt;char,int&amp;gt;::iterator it;&lt;br /&gt;
  int count = 0;&lt;br /&gt;
  // insert some values:&lt;br /&gt;
  mymap['a']=10;&lt;br /&gt;
  mymap['b']=20;&lt;br /&gt;
  mymap['c']=30;&lt;br /&gt;
  mymap['d']=40;&lt;br /&gt;
  mymap['e']=50;&lt;br /&gt;
  mymap['f']=60;&lt;br /&gt;
&lt;br /&gt;
  //suppose you decide to delete the 3rd item onwards&lt;br /&gt;
  for ( it=mymap.begin() ; it != mymap.end(); it++ ){&lt;br /&gt;
    if(count &amp;gt;=2){&lt;br /&gt;
       mymap.erase(it); // This statement is dangerous. When the iterator is used to delete the entry the reference that the iterator holds                                     &lt;br /&gt;
                        // is lost. Now we have lost the reference to our position in the map.&lt;br /&gt;
                        // Intuitively it seems iterator just specifies the entry in the map that has to be deleted. But the iterator is a &lt;br /&gt;
                        // pointer that holds a reference and it would jump to the beginning of the map.&lt;br /&gt;
    }&lt;br /&gt;
    count++&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java this can cause problems if the programmer is not careful.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Consider the following piece of code&lt;br /&gt;
&lt;br /&gt;
HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt; outer = new HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt;();&lt;br /&gt;
HashMap&amp;lt;String,String&amp;gt; inner = new HashMap&amp;lt;String,String&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;A&amp;quot;,&amp;quot;1&amp;quot;);&lt;br /&gt;
outer.add(&amp;quot;A1&amp;quot;,inner);&lt;br /&gt;
&lt;br /&gt;
inner.clear(); // This statement also erases the entry in the outer HashMap. This is because of the fact mentioned above.&lt;br /&gt;
               // When the inner hash map is added as an entry into the outer HashMap only a reference gets stored and not the actual HashMap          &lt;br /&gt;
               // Object.This is not the case with C++ STL which has copy semantics&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;B&amp;quot;,&amp;quot;2&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by listing the collections used in Java, which uses JCF and C++, which uses STL. We then compared JCF and STL and listed the advantages that JCF provides over STL. Finally we compared Java collections in library versus Ruby collections built into the language. For some purposes collections in library is better, and for other purposes collections in language is better.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51117</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51117"/>
		<updated>2011-09-26T02:26:01Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Manipulation of container objects using Iterators */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Extension capability===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the case in java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
  map&amp;lt;char,int&amp;gt; mymap;&lt;br /&gt;
  map&amp;lt;char,int&amp;gt;::iterator it;&lt;br /&gt;
  int count = 0;&lt;br /&gt;
  // insert some values:&lt;br /&gt;
  mymap['a']=10;&lt;br /&gt;
  mymap['b']=20;&lt;br /&gt;
  mymap['c']=30;&lt;br /&gt;
  mymap['d']=40;&lt;br /&gt;
  mymap['e']=50;&lt;br /&gt;
  mymap['f']=60;&lt;br /&gt;
&lt;br /&gt;
  //suppose you decide to delete the 3rd item onwards&lt;br /&gt;
  for ( it=mymap.begin() ; it != mymap.end(); it++ ){&lt;br /&gt;
    if(count &amp;gt;=2){&lt;br /&gt;
       mymap.erase(it); // This statement is dangerous. When the iterator is used to delete the entry the reference that the iterator holds                                     &lt;br /&gt;
                        // is lost. Now we have lost the reference to our position in the map.&lt;br /&gt;
                 // Intuitively it seems iterator just specifies the entry in the map that has to be deleted. But the iterator is a &lt;br /&gt;
                        // pointer that holds a reference and it would jump to the beginning of the map.&lt;br /&gt;
    }&lt;br /&gt;
    count++&lt;br /&gt;
  }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java this can cause problems if the programmer is not careful.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Consider the following piece of code&lt;br /&gt;
&lt;br /&gt;
HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt; outer = new HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt;();&lt;br /&gt;
HashMap&amp;lt;String,String&amp;gt; inner = new HashMap&amp;lt;String,String&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;A&amp;quot;,&amp;quot;1&amp;quot;);&lt;br /&gt;
outer.add(&amp;quot;A1&amp;quot;,inner);&lt;br /&gt;
&lt;br /&gt;
inner.clear(); // This statement also erases the entry in the outer HashMap. This is because of the fact mentioned above.&lt;br /&gt;
               // When the inner hash map is added as an entry into the outer HashMap only a reference gets stored and not the actual HashMap          &lt;br /&gt;
               // Object.This is not the case with C++ STL which has copy semantics&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;B&amp;quot;,&amp;quot;2&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by listing the collections used in Java, which uses JCF and C++, which uses STL. We then compared JCF and STL and listed the advantages that JCF provides over STL. Finally we compared Java collections in library versus Ruby collections built into the language. For some purposes collections in library is better, and for other purposes collections in language is better.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51108</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51108"/>
		<updated>2011-09-26T02:07:15Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Extension capability===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the casein java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java this can cause problems if the programmer is not careful.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Consider the following piece of code&lt;br /&gt;
&lt;br /&gt;
HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt; outer = new HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt;();&lt;br /&gt;
HashMap&amp;lt;String,String&amp;gt; inner = new HashMap&amp;lt;String,String&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;A&amp;quot;,&amp;quot;1&amp;quot;);&lt;br /&gt;
outer.add(&amp;quot;A1&amp;quot;,inner);&lt;br /&gt;
&lt;br /&gt;
inner.clear(); // This statement also erases the entry in the outer HashMap. This is because of the fact mentioned above.&lt;br /&gt;
               // When the inner hash map is added as an entry into the outer HashMap only a reference gets stored and not the actual HashMap          &lt;br /&gt;
               // Object.This is not the case with C++ STL which has copy semantics&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;B&amp;quot;,&amp;quot;2&amp;quot;)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by listing the collections used in Java, which uses JCF and C++, which uses STL. We then compared JCF and STL and listed the advantages that JCF provides over STL. Finally we compared Java collections in library versus Ruby collections built into the language. For some purposes collections in library is better, and for other purposes collections in language is better.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51107</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=51107"/>
		<updated>2011-09-26T02:05:55Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Pass by reference versus pass by value */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Extension capability===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the casein java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java this can cause problems if the programmer is not careful.&lt;br /&gt;
&lt;br /&gt;
Consider the following piece of code&lt;br /&gt;
&lt;br /&gt;
HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt; outer = new HashMap&amp;lt;String, HashMap&amp;lt;String,String&amp;gt;&amp;gt;();&lt;br /&gt;
HashMap&amp;lt;String,String&amp;gt; inner = new HashMap&amp;lt;String,String&amp;gt;();&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;A&amp;quot;,&amp;quot;1&amp;quot;);&lt;br /&gt;
outer.add(&amp;quot;A1&amp;quot;,inner);&lt;br /&gt;
&lt;br /&gt;
inner.clear(); // This statement also erases the entry in the outer HashMap. This is because of the fact mentioned above.&lt;br /&gt;
               // When the inner hash map is added as an entry into the outer HashMap only a reference gets stored and not the actual HashMap          &lt;br /&gt;
               // Object.This is not the case with C++ STL which has copy semantics&lt;br /&gt;
&lt;br /&gt;
inner.add(&amp;quot;B&amp;quot;,&amp;quot;2&amp;quot;)&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by listing the collections used in Java, which uses JCF and C++, which uses STL. We then compared JCF and STL and listed the advantages that JCF provides over STL. Finally we compared Java collections in library versus Ruby collections built into the language. For some purposes collections in library is better, and for other purposes collections in language is better.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=50593</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=50593"/>
		<updated>2011-09-25T17:43:21Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Extension capability===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the casein java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java if an one tries to access an object of a container that was just deleted , since we are using a reference this would result in error.&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== Conclusion ==&lt;br /&gt;
We started by listing the collections used in Java, which uses JCF and C++, which uses STL. We then compared JCF and STL and listed the advantages that JCF provides over STL. Finally we compared Java collections in library versus Ruby collections built into the language. For some purposes collections in library is better, and for other purposes collections in language is better.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=50587</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=50587"/>
		<updated>2011-09-25T17:20:50Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Extension capability===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the casein java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java if an one tries to access an object of a container that was just deleted , since we are using a reference this would result in error.&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=49568</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=49568"/>
		<updated>2011-09-19T20:09:05Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Collections in Java are more extensible than in STL===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the casein java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java if an one tries to access an object of a container that was just deleted , since we are using a reference this would result in error.&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=48570</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=48570"/>
		<updated>2011-09-09T02:55:59Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
'''Authors'''&lt;br /&gt;
* Dilip Devaraj&lt;br /&gt;
* Srinath Sridhar&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
In this article we compare and contrast the two most popular collections frameworks/libraries in use today, C++ STL and Java Collections Framework (JCF). Also we compare collections in Ruby which does not have a formal collections framework against C++ and Java which define a formal framework/library for collections.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Collections in Java are more extensible than in STL===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the casein java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
===Pass by reference versus pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java if an one tries to access an object of a container that was just deleted , since we are using a reference this would result in error.&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=47672</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=47672"/>
		<updated>2011-09-08T16:33:47Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Java Collections Framework (JCF) */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
'''Authors'''&lt;br /&gt;
* Dilip Devaraj&lt;br /&gt;
* Srinath Sridhar&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming] developed by Alexander Stepanov in the early 80s. At that time Ada was the only language which had support for generics. An initial generic library for list processing in Ada was developed by Alexander Stepanov and David Musser. However Ada did not achieve widespread acceptance by the programming community. As C/C++ became more widespread attention was given to developing a generic library in C++. Finally a proposal was made to the ANSI/ISO committee in 1993 and the C++ STL was finally accepted in 1994. &lt;br /&gt;
&lt;br /&gt;
In the case of Java the initial versions prior to JDK-1.2 did not have a collections framework. These versions just defined Vectors and HashTables which were used to group objects together. This is reminiscent of the way things are done in languages such as Ruby, Python etc. The formal collections framework was introduced in 1998 with JDK-1.2 which borrowed a lot form Doug Lea's ''Collections package''. The goal of this framework was to be consistent with C++ STL. But soon Sun Microsystems decided that Java needed a compact collections framework and consistency with C++ STL was no longer a priority. This led to the development of the Java Collections Framework as we know it today.&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following: List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Collections in Java are more extensible than in STL===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the casein java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
===Pass by reference Vs Pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java if an one tries to access an object of a container that was just deleted , since we are using a reference this would result in error.&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=47658</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1b ds</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1b_ds&amp;diff=47658"/>
		<updated>2011-09-08T16:14:46Z</updated>

		<summary type="html">&lt;p&gt;Ddilipd: /* Readability */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Cover the history of Collections frameworks back to the late 1970s or early 1980s, and how they were retrofitted to various languages.  Discuss the advantage of a standard Collections framework (e.g., Java) vs. several competing frameworks (e.g., C++), and the advantage of collections built into the language (e.g., Ruby) vs. collections as class libraries.  Give examples to illustrate the advantages you identify.&lt;br /&gt;
&lt;br /&gt;
'''Authors'''&lt;br /&gt;
* Dilip Devaraj&lt;br /&gt;
* Srinath Sridhar&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
A collection refers to a group of data items which have some commonality like a &amp;quot;a bunch of objects stored in a structured manner&amp;quot;. Collections are very common in daily life, some examples would be a collection of science fiction books, the names of employees in a given department etc. Given that object oriented design concepts try to model the real world, it is natural to include support for creating and manipulating collections in languages which support object oriented development. Collections allows you to organize data in memory in various convenient ways.&lt;br /&gt;
Example : a simple list of strings, a mapping or association of strings to strings (e.g. country names to the names of their capitals);&lt;br /&gt;
&lt;br /&gt;
Almost all major programming and scripting languages that are used today such as [http://en.wikipedia.org/wiki/Perl Perl], [http://en.wikipedia.org/wiki/Python_%28programming_language%29 Python]], [http://en.wikipedia.org/wiki/JavaScript JavaScript], [http://en.wikipedia.org/wiki/PHP PHP], [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby], [http://en.wikipedia.org/wiki/C%2B%2B C++] and [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] have support for collections in some form or the other. Some languages have liner arrays (which can have different types of elements) and associative arrays built into the language whereas some other languages provide support through external libraries.&lt;br /&gt;
&lt;br /&gt;
==History==&lt;br /&gt;
The history of collection frameworks can be analyzed in two aspects. Languages which have some basic collection containers built into them and languages with a formal collection framework. A collection framework may be defined as a generic reusable collection of classes which implements data structures and algorithms to create and manipulate groups of related objects. Few languages support a formal collections framework. Most of the modern programming languages have sequential arrays and associative array's built into them. A programmer may use these basic containers to create their own custom collection classes. A comparison of programming languages that implement associative arrays can be found [http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28mapping%29 here].&lt;br /&gt;
&lt;br /&gt;
The history of a collections framework or a collections library originate from ideas related to [http://en.wikipedia.org/wiki/Generic_programming generic programming].&lt;br /&gt;
&lt;br /&gt;
=='''Java Collections Framework (JCF)'''==&lt;br /&gt;
&lt;br /&gt;
[[Image:Jcf.gif]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Java Collections Framework is a library of classes that implement collections. The collections framework also provides utility methods to perform functions such as sorting a list of data.The collections in Java are mainly the following List, Set, Map and Queue. Java provides these collections as interfaces from which one can write their own classes or can use the inbuilt Java classes that implement these interfaces.&lt;br /&gt;
&lt;br /&gt;
===List===&lt;br /&gt;
List is a collection of objects that has a fixed order (when we add an object to the list, it will stay in the place we put it), and allows objects to be referred to by position.Duplicate elements are allowed in a list. The  general-purpose List implementations are  [http://download.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html ArrayList] and [http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedList.html LinkedList].&lt;br /&gt;
&lt;br /&gt;
===Set===&lt;br /&gt;
A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.The Java platform contains three general-purpose Set implementations: [http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html HashSet], [http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html TreeSet], and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html LinkedHashSet].&lt;br /&gt;
&lt;br /&gt;
===Map===&lt;br /&gt;
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. Maps are defined by the java.util.Map interface in Java. The three general-purpose Map implementations are [http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html HashMap], [http://download.oracle.com/javase/6/docs/api/java/util/TreeMap.html TreeMap] and [http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html LinkedHashMap]. The java.util.Map interface is extended by its subinterface, java.util.SortedMap. This interface defines a map that's sorted by the keys provided.&lt;br /&gt;
&lt;br /&gt;
===Queue===&lt;br /&gt;
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.  LinkedList implements the Queue interface, providing first in, first out (FIFO) queue operations.&lt;br /&gt;
&lt;br /&gt;
=='''C++ Standard Template Library(STL)'''==&lt;br /&gt;
C++ standard template library is a software library that provides implementations of some basic containers for storing collections of related objects as well as algorithms to perform operations on the elements in these containers. All the classes in C++ STL are generic and can be used with any user defined or primitive data types. In general the C++ STL has four major components.&lt;br /&gt;
&lt;br /&gt;
===Containers===&lt;br /&gt;
These are classes which are used to store other objects. Taking an example suppose there is a “jar of jellybeans”, the jar can be thought of as the container while the jelly beans are the objects that are stored in the container. Most collections automatically resize depending on the number of elements in them.The C++ STL provides a number of such classes which can be classified into two categories&lt;br /&gt;
&lt;br /&gt;
====Sequence Containers====&lt;br /&gt;
These containers impose a strict linear order on the elements. Sequence containers support insertions and deletions (either at the ends or at a random position) using an index. Some examples of sequence containers are vector, list, dequeue etc. &lt;br /&gt;
====Associative containers====&lt;br /&gt;
These containers store key value pairs and each object stored in an associative container is mapped to a specific key. In other words associative containers perform insertions and deletions based on a key. Some examples of associative containers are set, map, hash map, multiset etc.&lt;br /&gt;
&lt;br /&gt;
===Algorithms===&lt;br /&gt;
The C++ STL contains a large collection of algorithms that can be used to manipulate the data contained in the container. Continuing from the earlier “jar of jelly beans” example, suppose you wanted to count the number of red colored jelly beans. Or you wanted to change the color of all the jelly beans to red the algorithms in STL allow you to accomplish this.&lt;br /&gt;
&lt;br /&gt;
An important thing to note is that the algorithms in STL are decoupled from the container. This means that there is only one definition of the function which implements the algorithm. This works for any valid container containing any any valid set of objects. Analogous to our example the function to count the number of red jelly beans also works for a “bucket containing colored pebbles”.&lt;br /&gt;
&lt;br /&gt;
The algorithms contained in STL can be classified into two categories&lt;br /&gt;
====Non-Mutating====&lt;br /&gt;
Those which do not change the collection in any way. Examples include count, find, for each etc.&lt;br /&gt;
====Mutating====&lt;br /&gt;
Those which modify the contents of the collection in some way. Examples include replace, copy, reverse etc.&lt;br /&gt;
===Iterators===&lt;br /&gt;
Iterators are an important part of the C++ STL. Iterators facilitate traversal through a container’s elements. The separation of algorithms from containers is achieved through the use of iterators. Iterators can be thought of as a generalization of pointers. All the algorithms make use of iterators as function arguments. There are 5 types of iterators in STL. These differ in the way they traverse through the elements in the container.&lt;br /&gt;
&lt;br /&gt;
===Functor===&lt;br /&gt;
A functor or functional object is an object that can be called as a function. This is in essence similar to function pointers in C. A functor is any class that overloads the operator() function. Such a class is most commonly used to define custom comparison functions to compare two objects. This is similar to “comparator” in  JAVA.&lt;br /&gt;
&lt;br /&gt;
=='''JCF versus STL'''== &lt;br /&gt;
===Quality of implementation===&lt;br /&gt;
Java is standardised and have formalized methods such as Java community process(JCP) and Java Specification request (JSR) to define revisions of java platforms. C++ only gives a defining standard and one can have different implementations of that standard. Hence different implementations can be incompatible.&lt;br /&gt;
&lt;br /&gt;
===Portability===&lt;br /&gt;
This is a direct consequence of the fact that standards are available in Java and not in C++. &lt;br /&gt;
The following is a list of various [http://en.wikipedia.org/wiki/List_of_C%2B%2B_template_libraries STL libraries ]. These may have some common templates which might not necessarily be interoperable. In contrast the implementations of JCF are standardized and they will be portable as long as versions remain the same.&lt;br /&gt;
&lt;br /&gt;
===Better optimization of containers===&lt;br /&gt;
In C++ STL the algorithms (i.e functions which manipulate the data) are completely decoupled from the containers it is not possible to optimize containers for specific purposes.  In JCF since the algorithms are defined as interfaces it is easy to provide specific implementations based on requirements. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations. The only way to optimize in STL is to create new containers which are tied together with the algorithms.&lt;br /&gt;
&lt;br /&gt;
===More number of methods in STL===&lt;br /&gt;
STL has more number of methods than Java for collections. This is because STL has [http://www.sgi.com/tech/stl/table_of_contents.html separate methods] for containers and algorithms used for containers like Non-mutating algorithms, Mutating algorithms, Sorting&lt;br /&gt;
&lt;br /&gt;
===Collections in Java are more extensible than in STL===&lt;br /&gt;
STL collections are difficult to extend as the base classes are not declared as virtual. In Java since the basic collections are interfaces, it is easy to implement the interfaces in a class, and extend from that.&lt;br /&gt;
&lt;br /&gt;
===Manipulation of container objects using Iterators ===&lt;br /&gt;
C++ STL uses iterators to iterate through the items. Iterators themselves are generalizations of pointers. This leads to problems when one has to manipulate the items in the container, especially if the items have to be removed. It is tricky to iterate through the container and delete objects within the same loop. This is not the casein java since memory cannot be directly manipulated by the programmer.&lt;br /&gt;
&lt;br /&gt;
===Pass by reference Vs Pass by value===&lt;br /&gt;
Containers in STL is accessed using copy semantics, thereby providing both efficiency and type safety, while in Java collections are accessed via references (or pointers). In Java if an one tries to access an object of a container that was just deleted , since we are using a reference this would result in error.&lt;br /&gt;
&lt;br /&gt;
=='''Collections in languages versus library'''==&lt;br /&gt;
We are comparing collections inbuilt into the Ruby language versus Java’s collection libraries.&lt;br /&gt;
&lt;br /&gt;
===Operators vs Methods===&lt;br /&gt;
In languages with collections built into them many operations may be performed using operators instead of calling functions. Consider an associative array, called hash in ruby and map in java.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt; &lt;br /&gt;
Assoc_array[&lt;br /&gt;
	{“hello”, “world”}&lt;br /&gt;
	{“good”,”day”}&lt;br /&gt;
]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a language with collections implemented as a class library one would  use a function like “get(key)” to retrieve the value associated with a key. When there is language support one can use Assoc_array[key] to retrieve the value of the key.Now suppose we would like to extend the get function to do something different, in a language like java we can simply write another function or create a different implementation of the associative array which overrides the get function defined in the interface.  Now in case of a language where the get is implemented using an operator we should either overload the default behavior of the operator or we have to define a custom operator to do this. In general it is much easier to overload a function than to overload an operator, Further not all languages allow operator overloading.&lt;br /&gt;
&lt;br /&gt;
===Import===&lt;br /&gt;
In Ruby since collections are part of the language , therefore a developer need not include library for common functionalities while writing a program. In case of collections which are present in libraries like Java, one needs to import the libraries before executing the code. This can become a hassle for a Java developer if one does not know the name of the library to import for using a collection.&lt;br /&gt;
&lt;br /&gt;
===Operator Overloading===&lt;br /&gt;
In Java we do not have operator overloading, but instead use methods to do the equivalent operations. Ruby has overloading where one can override , say a + operator.&lt;br /&gt;
By not having operator overloading Java can have clearer code.This is because when one uses a + overloaded operator, we can get an unexpected behavior if internally it is coded to something else, say a subtraction. The number of operators that you can overload is very small and most of them is relevant to scalar operations. Additionally, the detail of the operation performed by operators may not be as meaningful in comparison to a good method name.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Test&lt;br /&gt;
 def initialize x&lt;br /&gt;
   @x = x&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 def +(y)&lt;br /&gt;
   @x - y&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
a = Test.new 5&lt;br /&gt;
puts(a + 3)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In above example instead of getting a result of 8 due to the + operator being overloaded in a wrong way we instead get a result of 2&lt;br /&gt;
&lt;br /&gt;
===Performance===&lt;br /&gt;
Collections in Ruby is slower than in Java as Ruby is a dynamically typed language. , therefore &lt;br /&gt;
in Ruby type checking happens at run-time which would slow down collection performance.&lt;br /&gt;
&lt;br /&gt;
===Verbosity===&lt;br /&gt;
In Ruby since one uses operator for hash-tables, the code is less verbose and therefore easier to type:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 h[lastname] = firstname &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
In Java one has to type a method name which increases the verbosity:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
hashmap.put(lastname)= firstname&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Readability===&lt;br /&gt;
In Java when one has nested methods on collections, the code is easier to read than in Ruby when one has nested operators on collections within a single line. The Java code is easier to debug also as one can look at the values of the variables assigned on the nested methods.&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
[1] http://download.oracle.com/javase/tutorial/collections/intro/index.html&lt;br /&gt;
&lt;br /&gt;
[2]http://www.javamex.com/tutorials/collections/index.shtml&lt;br /&gt;
&lt;br /&gt;
[3]http://en.wikipedia.org/wiki/Java_collections_framework&lt;br /&gt;
&lt;br /&gt;
[4]http://www.sgi.com/tech/stl/index.html&lt;br /&gt;
&lt;br /&gt;
[5]http://en.wikipedia.org/wiki/Standard_Template_Library&lt;br /&gt;
&lt;br /&gt;
[6]http://download.oracle.com/javase/6/docs/technotes/guides/collections/overview.html&lt;br /&gt;
&lt;br /&gt;
[7]http://java.dzone.com/articles/why-java-doesnt-need-operator&lt;br /&gt;
&lt;br /&gt;
[8]http://www.ruby-doc.org/core/&lt;/div&gt;</summary>
		<author><name>Ddilipd</name></author>
	</entry>
</feed>