-
Notifications
You must be signed in to change notification settings - Fork 5
Lecture 02
You should always have on mind that with great power comes great responsibility.
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
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.
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
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"
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"