首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > Ruby Rails >

Ruby 学习札记 -块blocks

2012-08-21 
Ruby学习笔记 --块blocks{} 单行的用;do...end 用block可以带参数,也可以不带参数,参数使用||,举例说明:[C

Ruby 学习笔记 --块blocks
{} 单行的用;do...end 用
block可以带参数,也可以不带参数,参数使用||,

举例说明:
[Crabby@Crabby-Lee Book]$ irb
1.9.3-p125 :001 > sum = 0
=> 0
1.9.3-p125 :002 > (1..5).each do |v|
1.9.3-p125 :003 >     name = 'smile'
1.9.3-p125 :004?>   sum +=v
1.9.3-p125 :005?>   end
=> 1..5
上例中name是块内的变量,离开块便不可以访问;块内可以访问块外的变量

1.9.3-p125 :016 > name = 'oooo'   
1.9.3-p125 :017 > sum = 0
1.9.3-p125 :018 > (1..5).each do |v| 
1.9.3-p125 :019 >     name = 'inside' //如果没有显示定义块内的局部变量;name,则name将修改全局变量
1.9.3-p125 :020?>   sum +=v
1.9.3-p125 :021?>   end
1.9.3-p125 :022 > p sum
1.9.3-p125 :023 > p name //name 输出为inside,


Blocks
you assign a name to a block,the code in the block is always enclosed within braces({}),always invoked from a function with the same name as that of the block.This means that if you have a block with the nametest,then you use the function nametest to invoke this block.


block_name
{
  statement1,
  statement2
}



1.9.3-p125 :001 > def test
1.9.3-p125 :002?>   puts "you  r in the method"
1.9.3-p125 :003?>   yield
1.9.3-p125 :004?>   puts "you are again back to the method"
1.9.3-p125 :005?>   yield
1.9.3-p125 :006?>   end
=> nil
1.9.3-p125 :007 > test {p "Fuck"}
you  r in the method
"Fuck"
you are again back to the method
"Fuck"
=> "Fuck"



有参数的调用:
def test
   yield 5
   puts "You are in the method test"
   yield 100
end
test {|i| puts "You are in the block #{i}"}


暂时未学习,待补充.
块与方法


热点排行