Ruby

From Suhrid.net Wiki
Jump to navigationJump to search

Philosophy

  • Focus is on the programmer rather than the machine. i.e. maximize programmer efficiency.
  • Principle of least astonishment - behave in such a way that minimized the confusion of experienced Ruby programmers.
  • Ruby is an object-oriented scripting language.
  • Multi paradigm :
    • Scripting : automate tasks within some environment
    • Imperative : traditional control structures
    • Object oriented : everything is an object
    • Functional : Also exists. Computation proceeds via the evaluation of functions that depend only on their input, not program state.

Classes and Inheritance

class MyClass
   @boo #instance variable
   def my_method
     @foo = 2 #instance variable
   end
end
mc = MyClass.new #create a myclass object
mc.my_method     #calls the method
mc.boo           #error, not allowed to access variable
  • An instance variable can only be accessed or modified within a method definition.
class MyClass
 def boo  #getter method
   return @boo
 end

 def boo=(val) #setter method
   @boo = val
 end
end
mc = MyClass.new #create a myclass object
boo = 1 #calls the setter method
boo  #calls the getter method
  • Shortcut
class Person
   attr_accessor :first_name, :last_name #creates instance variables and getter/setter methods
end
  • No return values specified in the method. The value of the last expression executed in the method is its return value.
def min (x,y)
  if x < y then x else y end
end
  • When invoking a method, parentheses are optional.
  • Class methods (static methods) are created in the same way as normal methods, except are prefixed with keyword "self".
  • Array.methods returns all methods in the Array class.
  • Ruby convention is to use the last character of a method name to indicate its behaviour. e.g ? is used to indicate return of boolean. "!" is changing the state of the object.
  • self refers to the current object. (similar to this)
  • Only single inheritance is supported, but mixin capability offers multiple inheritance.
  • Classes are NEVER closed, always add more instance vars, methods etc. (Both built in and custom classes)
class Fixnum #built in ruby class
 def previous #add a new method
   return self -1
 end
end

32.previous #returns 31

Access

  • Within a class definition
  • public - no access control
  • protected - only be invoked by objects of the defining class and its subclasses
  • private - only be called in the context of the current object with no reference on LHS. Thus can only be used on self. Two objects of the same class cannot call each others private methods.
  • Only invoke a private method from within another method of the class.
  • By default every method is public and variables are protected.