1 added
11 removed
Original
2026-01-01
Modified
2026-02-26
1
-
<h3>Класс - это объект Class</h3>
1
+
class Cat def self.my_attr_accessor *attributes attributes.each do |attribute| # Getter define_method attribute do self.instance_variable_get "@#{attribute}" end ######## # Setter define_method "#{attribute}=" do |value| self.instance_variable_set "@#{attribute}", value end ######## end end my_attr_accessor :name, :age, :weight def initialize name, age, weight @name, @age, @weight = name, age, weight end end
2
-
class Cat end Dog = Class.new Cat.object_id Dog.object_id<h3>Поиск метода объекта</h3>
3
-
class Cat def count_legs 4 end end cat = Cat.new cat.class Cat.class cat.class.ancestors Cat.class.ancestors<h3>Метакласс</h3>
4
-
first_cat = Cat.new second_cat = Cat.new def first_cat.meow "meow" end first_cat.meow second_cat.meow first_cat.singleton_class second_cat.singleton_class first_cat.singleton_methods second_cat.singleton_methods<h3>Include</h3>
5
-
module Homable def has_home? true end end class Cat include Homable def has_home? false end end Cat.new.has_home? Cat.ancestors<h3>Prepend</h3>
6
-
module Homable def has_home? true end end class Cat prepend Homable def has_home? false end end Cat.new.has_home? Cat.ancestors<h3>Extend</h3>
7
-
module Homable def has_home? true end end class Cat extend Homable end Cat.has_home? ### define_method, instance_variable_get, instance_variable_set<h3>Добавление метода экземпляру</h3>
8
-
class Cat define_method 'eat' do |food| "#{food}'s yammy!" end end cat = Cat.new cat.eat 'whiskas'<h3>Чтение переменной экземпляра</h3>
9
-
class Cat def initialize string @color = string end end cat = Cat.new("black") cat.instance_variable_get "@color"<h3>Запись переменной экземпляра</h3>
10
-
class Cat end cat = Cat.new() cat.instance_variable_set "@color", "black"<h3>Добавление методов классу</h3>
11
-
class Cat def self.my_attr_accessor *attributes attributes.each do |attribute| # Getter define_method attribute do self.instance_variable_get "@#{attribute}" end ######## # Setter define_method "#{attribute}=" do |value| self.instance_variable_set "@#{attribute}", value end ######## end end my_attr_accessor :name, :age, :weight def initialize name, age, weight @name, @age, @weight = name, age, weight end end class StringInquirer < String private def method_missing(method_name, *arguments) if method_name.to_s.end_with?("?") self == method_name[0..-2] else super end end end mammal = StringInquirer.new('cat') mammal.cat? # true mammal.dog? # false mammal.methods.include? :cat? #false class User def log_vk_auth Loggers::VK.new.send_message end def log_facebook_auth Loggers::Facebook.new.send_message end def log_twitter_auth Loggers::Twitter.new.send_message end # с использованием active support %w(vk facebook twitter).each do |network| define_method "log(#{network}_auth" do "Loggers::#{network.capitalize}".constantize end end end