TAILIEUCHUNG - Ruby for Rails phần 8

Ở đây, "attr_reader" là một ví dụ của meta-programming trong Ruby: "attr" định nghĩa các phương thức dạng 'getter' và 'setter' của instance variables; "attr_reader": các phương thức dạng 'getter'. Và, câu lệnh cuối cùng trong một phương thức (method) là giá trị trả về, cho phép bỏ qua việc chỉ định 'return' một cách tường minh. | The eval family of methods 349 instance_eval instance_eval is a specialized cousin of eval. It evaluates the string or code block you give it changing self to be the receiver of the call to instance_eval. This code p self a p self outputs two different selfs main instance_eval is mostly useful for breaking in to what would normally be another object s private data particularly instance variables. Here s how to see the value of an instance variable belonging to any old object in this case the instance variable of @x of a C object class C def initialize @x 1 end end c puts @x This kind of prying into another object s state is generally considered impolite if an object wants you to know something about its state it provides methods through which you can inquire. Nevertheless because Ruby dynamics are based on the changing identity of self it s not a bad idea for the language to give us a technique for manipulating self directly. We ve saved the most useful of the eval family of methods for last class_eval synonym module_eval . The most useful eval class_eval . module_eval In essence class_eval puts you inside a class definition body c do def some_method puts Created in class_eval end end c ------- Output Created in class_eval 350 CHAPTER 13 Ruby dynamics However you can do some things with class_eval that you can t do with the regular class keyword Evaluate a string in class-definition context Open the class definition of an anonymous class other than a singleton class Gain access to variables in the surrounding scope The third item on this list is particularly worthy of note. When you open a class with the class keyword you start a new local variable scope. The block you use with class_eval however can see the variables created in the scope surrounding it. Look at the difference between the treatment of var an outer-scope local variable as between a regular class .

TAILIEUCHUNG - Chia sẻ tài liệu không giới hạn
Địa chỉ : 444 Hoang Hoa Tham, Hanoi, Viet Nam
Website : tailieuchung.com
Email : tailieuchung20@gmail.com
Tailieuchung.com là thư viện tài liệu trực tuyến, nơi chia sẽ trao đổi hàng triệu tài liệu như luận văn đồ án, sách, giáo trình, đề thi.
Chúng tôi không chịu trách nhiệm liên quan đến các vấn đề bản quyền nội dung tài liệu được thành viên tự nguyện đăng tải lên, nếu phát hiện thấy tài liệu xấu hoặc tài liệu có bản quyền xin hãy email cho chúng tôi.
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.