Sunday, March 18, 2012

Ruby Notes

I recently started learning Ruby as a part of "Software Engineering for Software as a Service" online course offered by  University of California, Berkeley.

Since I am mostly experienced with java, I found some differences to be interesting.
  • Ruby is object oriented, similar to Java. 
    • But everything is an object. Even primitive types such as integers are objects. 
    • Almost everything is a method call on some object. Even most operators are instance methods. You can do method calls on anything. 
      • 6.methods will return a list of methods that it will respond to.
      • 1+2 means we pass the objects operator + and the number 2 to the send method of object 1. 1.send(:+, 2)
  • Dynamically typed
    • Even though objects have types, variable don't have types. 
    • Also, there are no declarations either
    • That means, you just can use a variable without declaring first, and use it to store any type of object.
  • Identifier Conventions
    • Class names should UpperCamelCase similar to Java
    • But methods and variable names should use snake_case unlike java's camelCase
  • Ruby is pass-by-reference, since everything is an object. (whereas Java is pass-by-value.)
  • Metaprogramming
    • this basically means you can do some of the programming during the runtime, such as method definitions. 
    • Say there's an instance variable name. Instead of writing it's getter and setter, you can specify to create them during runtime using metaprogramming by: attr_accessor :name
  • Iterators
    • Iterations play a big role in Ruby. 
    • In Java, we usually run a loop with an index and do something with the object for the index in each iteration.
    • In Ruby, iterating with an index is discouraged. Rather, we let objects manage their own traversal.
    • my_array.each do |elt| { } end
  • Duck Typing
    • An object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.
    • For example, you can call sort on arrays with different type of objects, strings, hashes, if they respond to the method somehow, without considering their types.
  • Mix-ins
    • This is used to achieve duck typing.
    • In Ruby, there are things called Modules, A module is a collection of class & instance
      methods that are not actually a class. Therefore you cannot instantiate it
    • But by including modules in your class you can resuse (mix) their methods
    • class A < B ; include MyModule ; end . A.foo first search A, MyModule and finally B.
Here are some of the resources for getting started with Ruby:
  1. Ruby in Twenty Minutes
  2. Try Ruby
Ruby Installer is a nice packaging that makes it easy to install Ruby on Windows