Classes

Basic

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ класса

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)

Use method-accessors

Getters

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

Setters

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

Inheritance

class ChildClass < ParentClass
end

ΠŸΠ΅Ρ€Π΅ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΡΠ΅ΠΌ конструктор ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ

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

АнонимныС классы (Π½Π΅ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½Π½Ρ‹Π΅)

=begin
    Анонимный класс
=end

fred = Class.new do
    def method
        "hello"
    end
end

a = fred.new
puts a.method

Public, private and protected methods

МоТно Ρ‡Π΅Ρ€Π΅Π· self ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΡΡ‚ΡŒ ΠΏΡ€ΠΈΠ²Π°Ρ‚Π½Ρ‹Π΅ ΠΌΠ΅Ρ‚ΠΎΠ΄Ρ‹

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

А ΠΌΠΎΠΆΠ½ΠΎ Ρ‡Π΅Ρ€Π΅Π· public/private Π΄ΠΈΡ€Π΅ΠΊΡ‚ΠΈΠ²Ρ‹

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

Last updated