Copy class BankAccount
def initialize ()
end
def test_method
puts "The class is working"
end
end
account = BankAccount . new ()
account . test_method # Exec method
=> The class is working
Accessors (getters and setters)
Copy class BankAccount
def myAccessor
@myAccessor = "test"
end
def initialize ()
end
def test_method
puts "The class is working"
puts myAccessor
end
end
account = BankAccount . new ()
account . myAccessor # Init accessor
account . test_method # Exec method
=> The class is working
=> test
Copy class BankAccount
# Getter
def myValue
@value
end
# Setter
def myValue= ( val )
@value = val
end
def initialize ()
end
end
acc = BankAccount . new ()
acc . myValue = "test"
puts acc . myValue
Copy class ChildClass < ParentClass
end
ΠΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΠΌ ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡ ΠΏΠΎ ΡΠΌΠΎΠ»ΡΠ°Π½ΠΈΡ
Copy class Class # ΠΠ΅ΡΠΎΠ»ΡΠ½ΡΠΉ Π²ΡΡΡΠΎΠ΅Π½Π½ΡΠΉ ΠΊΠ»Π°ΡΡ Class
alias old_new new # ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΠΌ Π΄Π΅ΡΠΎΠ»ΡΠ½ΡΠΉ ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡ
def new ( * args )
print "Creating a new " , self . name , "\n"
old_new( * args)
end
end
=begin
ΠΠΌΠ΅Π½ΠΎΠ²Π°Π½Π½ΡΠΉ ΠΊΠ»Π°ΡΡ
=end
class Name
# Some code ...
end
n = Name . new
ΠΠ½ΠΎΠ½ΠΈΠΌΠ½ΡΠ΅ ΠΊΠ»Π°ΡΡΡ (Π½Π΅ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½Π½ΡΠ΅)
Copy =begin
ΠΠ½ΠΎΠ½ΠΈΠΌΠ½ΡΠΉ ΠΊΠ»Π°ΡΡ
=end
fred = Class . new do
def method
"hello"
end
end
a = fred . new
puts a . method
Public, private and protected methods
Copy class PrivateMethod
def pub
"Public"
end
def self.priv
"Private"
end
end
p = PrivateMethod . new
puts p . pub
puts p . priv
=begin
$ ruby classes.rb
Public
Traceback (most recent call last):
classes.rb:16:in `<main>': undefined method `priv' for #<PrivateMethod:0x00007f9fc301d5c8> (NoMethodError)
=end
Copy class PrivateMethod
public
def pub
"Public"
end
protected
def protected_method
"Protected"
end
private
def priv
"Private"
end
def priv2
"Another private method"
end
end
p = PrivateMethod . new
puts p . pub
puts p . priv
=begin
$ ruby classes.rb
Public
Traceback (most recent call last):
classes.rb:16:in `<main>': undefined method `priv' for #<PrivateMethod:0x00007f9fc301d5c8> (NoMethodError)
=end