Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
215,45 KB
Nội dung
! " # $# ! %&& ! ' ! ( ) * !&+& ,!+ ! '&& $! *+ $ -./ 0 , 0 0 ! 12$ $! 3+) 4*+' ()+1 ! (+ ( ' 5$$ 2"0$ !2 %*67*6" ,08 %" *"0$! 9.0::. 9.;: 9.<: '()+ $ () 5= 8$ '>$ +" ) 3,! (+ *?23$ 4$4! @'A%BC?2! , " 5 5 '$D9DD;8$ $+$ '?2,? !% 2 ! !* 8 ! 5 [...]... this module needs to define and set a @value instance variable a module could invoke methods defined not in the module itself but in the class that it will be mixed with # Convert a integer value to English 02.module Stringify 03. # Requires an instance variable @value 04. def stringify 05. if @value == 1 06. "One" 07. elsif @value == 2 08. "Two" 09. elsif @value == 3 10. "Three"... 6 7 8 9 [ 1, 1, 2, 3, 5 ].each {|val| print val, " " } Produces: 1 1 2 3 5 songList.each do |aSong| aSong.play end Dynamic Programming Duck Typing Based on signatures, not class inheritance In Ruby, we rely less on the type (or class) of an object and more on its capabilities Duck Typing is a type of dynamic typing in which the object’s current set of methods and properties determines the... # Check whether the object defines the to_str method puts ('A string'.respond_to? :to_str) # => true puts (Exception.new.respond_to? :to_str) # => true puts (4.respond_to? :to_str) # => false The above example is the simplest example of Ruby' s philosophy of "duck typing:" if an object quacks like a duck (or acts like a string), just go ahead and treat it as a duck (or a string) Whenever possible, you should treat objects according to... constant offset Dynamic Language Dynamic Behavior ◦ ◦ ◦ ◦ Reflection Scope Reopening (Kind of like AOP) Eval Breakpoint debugger Reflection One of the many advantages of dynamic languages such as Ruby is the ability to introspect -to examine aspects of the program from within the program itself Some call this feature reflection We might discover: ◦ ◦ ◦ ◦ what objects it contains, the current class... #=> String class Foo end Foo.class #=> Class Foo is a constant known to the system as a class Looking at Objects Have you ever craved the ability to traverse all the living objects in your program? Ruby lets you perform this trick with ObjectSpace::each_object For example, to iterate over all objects of type Numeric, you'd write the following a = 102.7 b = 95 # Won't be returned c = 12345678987654321... examining all living objects in the system, these turn up as well To get ObjectSpace to work from Netbeans use option –X+O (O as in Oreo) Right click on Project name, Select Properties Click Run Define Ruby Option Looking Inside Objects For instance, we can get a list of all the methods to which an object will respond r=1 10 num = 14 list = r.methods list.length # 60 list[0 3] # [exclude_end?, to_a,