Skip to content

Instantly share code, notes, and snippets.

@iliabylich
Last active November 20, 2018 00:04
Show Gist options
  • Save iliabylich/09dc068288267984950949ce8bd9605d to your computer and use it in GitHub Desktop.
Save iliabylich/09dc068288267984950949ce8bd9605d to your computer and use it in GitHub Desktop.
code samples from lecture
class Point
attr_reader :x, :y
def initialize(x ,y)
@x = x
@y = y
end
def [](attribute_name)
case attribute_name
when :x
@x
when :y
@y
else
raise "No atrtibute #{attribute_name}"
end
end
def +(other)
Point.new(
@x + other.x,
@y + other.y
)
end
end
a = Point.new(1 ,2)
def a.inspect
"Point 1, 2"
end
a[:y]
b = Point.new(3, 4)
c = a + b
module Logging
def initialize(*args)
puts "Created object with type #{self.class}, #{args}"
super
end
end
class Car
prepend Logging
def initialize(color)
puts "*" * 40
@color = color
end
end
class Human
prepend Logging
end
puts Car.new('white').inspect
puts Human.new.inspect
module M
def m1; super; end
end
class A
class << self
def m1; end
prepend M
end
end
A.m1
class A < Object
def m
end
end
A = Class.new(Object) do
def m
end
end
module M
def m
end
end
M = Module.new do
def m
end
end
def m(a, b = 1, *c, d:, e: 1, **f, &block)
p [a, b, c, d, e, f, block.call]
end
m(1, 2, 3, 4,d: 5, h: 100, whatever: "asd") { 123 }
def each_positive_numbers
yield 1, 2
yield 2
yield 3
# ...
end
each_positive_numbers { |n| puts n }
inc = lambda { |n| n + 1 }
inc.call(2)
# def proc(&block)
# block
# end
inc = ->(n) { n + 1 }
inc.call(2)
def inc(n)
n + 1
end
method(:inc).call(2)
@mikalai-yankouski
Copy link

mikalai-yankouski commented Nov 19, 2018

3.rb
почему если сделать prepend до определения синглтона модуль не будет вызываться

module M
  def m1
    puts 'module'
    super  	
  end
end

class A
  prepend M
  class << self
    def m1
    	puts 'class'
    end
  end
end

A.m1  =>  "class"

по идее

 class << self
  def m1; end
end

перезаписывает m1 включенный из prepend и становиться в method table раньше него, но почему? Получается что class << self ведет себя аналогично prepend?

@VladHurma
Copy link

VladHurma commented Nov 19, 2018

Дело в том, что prepend не находящийся в статической позиции, для своего срабатывания требует создать экземпляр класса(это почти как пытаться вызвать нестатический метод(экземпляра) - бесполезно)
Когда ты вызываешь класс без конструктора(как в твоем примере), код обращается автоматически к статической части класса, куда твой prepend не входил, посему и не выводил "method"
Наверное дело в этом

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment