Skip to content

Lecture 02

marekjelen edited this page Oct 4, 2011 · 21 revisions

Basics

Responsibility

You should always have on mind that with great power comes great responsibility.

Separating code into files

In Ruby code can be separated into files. To load code from file use require

require "somefile.extension"

File with extension [rb, so, o, dll, bundle, jar] can be addressed without the extension. Having a file called somefile.rb these two are equivalent

require "somefile"
require "somefile.rb"

The file, if it is not absolute path, will be looked from paths contained in $: variable. $: is Array and user is free to add it's own paths or delete others. Required files are tracked in variable $". If a path is already in $", than it will not be required again. $" is also Array and user is free to modify it.

Execution

Every line in Ruby is just execution of some methods inside some object. There is a top level context that is just simple instance of Object (required files are executed in this context).

For example:

class A
  puts "Hello world"
end

will print "Hello world" and define new class A. We can put executable code anywhere in Ruby. And everything is just an execution.

Context

As said before, everything in executed in some context. This context is know as current object and is always represented by self.

self.class
# => Object

class B
  self
end
# => Class

Class

Open classes

Unlike most languages, Ruby classes are open for modifications. This way programmer can modify behavior of classes defined by frameworks or Ruby itself.

class Clazz
  def call
    "A"
  end
end

class Clazz
  def call
    "B"
  end
end

Clazz.new.call()
# => "B" 

What is a class?

People unfamiliar with Ruby might ask, why is the precedent example valid and the answer is simple:

classes are objects

everything in Ruby is an object ... even a class. Don't you believe me? Try this example:

class A
  def self.call
    "A"
  end
end

class B
end

def B.call
  "B"
end

C = Class.new

class C
  def self.call
    "C"
  end
end

D = Class.new

def D.call
  "D"
end

A.call # => "A"
B.call # => "B"
C.call # => "C"
D.call # => "D"
Clone this wiki locally