ruby学习--block

 1 #当前块
 2 class Block
 3     def a_method
 4         return yield if block_given?
 5         'no block'
 6     end
 7 end
 8 obj=Block.new
 9 puts "#{obj.a_method}"
10 puts "#{obj.a_method {"here's a block!"}}"
 1 #闭包
 2 class Greeter
 3     def initialize(name)
 4         @name=name
 5     end
 6     def name
 7         @name
 8     end
 9     def name=(new_name)
10         @name=new_name
11     end
12 end
13 g=Greeter.new("Barney")
14 puts g.name     
15 g.name="Betty"
16 puts g.name       
 1 #切换作用域
 2 v1=1
 3 class MyClass
 4     v2=2
 5     local_variables                    
 6     #puts "#{local_variables}"       #[:v2]  
 7     def my_method
 8         v3=3
 9         local_variables
10         #puts "#{local_variables}"    #[:v3]
11     end
12     local_variables
13     #puts "#{local_variables}"        #[:v2]
14 
15 end
16 obj=MyClass.new
17 obj.my_method                        #[:v3]
18 puts "#{local_variables}"            #[:v1, :obj]

 

posted @ 2014-08-27 18:01  翌子涵  阅读(138)  评论(0编辑  收藏  举报