首页 > 代码库 > ruby学习--block

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 {"heres 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_name11     end12 end13 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_variables10         #puts "#{local_variables}"    #[:v3]11     end12     local_variables13     #puts "#{local_variables}"        #[:v2]14 15 end16 obj=MyClass.new17 obj.my_method                        #[:v3]18 puts "#{local_variables}"            #[:v1, :obj]

 

ruby学习--block