Tôi muốn biết các biến mẫu của một mô-đun Ruby hoạt động như thế nào trên nhiều lớp mà 'trộn' nó 'trong'. Tôi đã viết mã mẫu để kiểm tra:Biến thể của một mô-đun được chia sẻ giữa lớp với mixin?
# Here is a module I created with one instance variable and two instance methods.
module SharedVar
@color = 'red'
def change_color(new_color)
@color = new_color
end
def show_color
puts @color
end
end
class Example1
include SharedVar
def initialize(name)
@name = name
end
end
class Example2
include SharedVar
def initialize(name)
@name = name
end
end
ex1 = Example1.new("Bicylops")
ex2 = Example2.new("Cool")
# There is neither output or complains about the following method call.
ex1.show_color
ex1.change_color('black')
ex2.show_color
Tại sao nó không hoạt động? Và ai đó có thể giải thích hành vi thực tế của @color
trên nhiều trường hợp Example$
là gì?
Giải thích khá rõ ràng! Vì vậy, nếu mô-đun tôi thiết kế là để trộn với các lớp khác. Tôi nên xác định 'instance variable' bên trong' instance method', là sự hiểu biết của tôi đúng chưa? – steveyang
Có, chỉ cần tính toán bản thân hiện tại là gì và sau đó bạn có thể hiểu vị trí của biến thể hiện. – megas
Cảm ơn. Tôi chỉ đang học Ruby hiện tại, không phải là phần tự hiện tại. Có vẻ ngôn ngữ thanh lịch hơn 'javaScript'. – steveyang