class SuperCat
def initialize ( height, weight, tail_color, head_color, legs_color )
@height , @weight , @tail_color , @head_color , @legs_color = height, weight, tail_color, head_color, legs_color
end
def SuperCat . white_cat ( height, weight )
new ( height, weight, "white" , "white" , "white" )
end
def SuperCat . black_cat ( height, weight )
new ( height, weight, "black" , "black" , "black" )
end
def SuperCat . big_cat ( tail_color, head_color, legs_color )
new ( 100, 100, tail_color, head_color, legs_color )
end
end
a = SuperCat . new ( 10, 15, "white" , "black" , "white" )
b = SuperCat . black_cat ( 13, 20 )
c = SuperCat . big_cat ( "white" , "red" , "red" )
p ( a ) ; p ( b ) ; p ( c )initialize method. Then we can use the block to initialize the object. We will use the instance_eval method instead of eval:class HyperCat
attr_accessor :name ,
:height , :weight , :age ,
:tail_color , :head_color , :legs_color
def initialize ( &block )
instance_eval &block
end
# ...
end
pussy = HyperCat . new do
self . name = "Pussy"
self . height = 10
self . weight = 12
self . age = 3.2
self . tail_color = "gray"
self . head_color = "gray"
self . legs_color = "white"
end
p pussyself , because the value assignment method always takes an explicit receiver to create a local variable.Module private method will help us.private two ways. If you call private without parameters in the body of the class, all the methods below will become private. Or you can pass the list of methods as symbols as private parameters:class Bank
def open_safe
# ...
end
def close_safe
# ...
end
private :open_safe , :close_safe
def make_withdrawal ( amount )
if access_allowed
open_safe
get_cash ( amount )
close_safe
end
end
# -
private
def get_cash
# ...
end
def access_allowed
# ...
end
endclone and dup methods create copies of the caller. The dup method only copies the contents of an object, while clone takes things like the singleton classes associated with an object:s1 = "cat"
def s1 . upcase
"CaT"
end
s1_dup = s1. dup
s1_clone = s1. clone
s1 #=> "cat"
s1_dup. upcase #=> "CAT" ( )
s1_clone. upcase #=> "CaT"module MyMod
def meth
puts " "
puts " ."
end
end
class MyClass
class << self # self MyClass
include MyMod
end
endextend method is useful to us - with it the example becomes much simpler:class MyClass
extend MyMod
end
MyClass . meth
class ExtraCat
attr_accessor :name , :age , :weight
def initialize ( name, age, weight )
@name , @age , @weight = name, age, weight
end
end
lucky = ExtraCat . new ( "Lucky" , 2, 4 )Struct class came in handy. As attr_accessor defines the necessary methods for us, and Struct defines classes that contain the same attributes. These classes are called structure templates .ExtraCat = Struct . new ( "ExtraCat" , :name , :age , :weight )
lucky = ExtraCat . new ( "Lucky" , 2, 4 )Source: https://habr.com/ru/post/49418/
All Articles