{} 单行的用;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}"}
暂时未学习,待补充.
块与方法
分享到:
相关推荐
Ruby的高级特性,如面向对象编程、元编程、块(blocks)、proc和lambda等,为编程提供了强大的表达力,但同时也给初学者带来了理解上的难度。作者可能会在笔记中列举一些常见的困惑,比如什么是元编程?块与proc和...
本资源“学习 Ruby 的笔记以及 Demo.zip”显然包含了关于Ruby编程的学习资料和一些实际示例代码,旨在帮助初学者理解并掌握Ruby的基础及进阶特性。 首先,让我们深入了解一下Ruby的核心特性: 1. 面向对象:Ruby是...
"ruby笔记2ruby笔记2ruby笔记2"可能是指一系列关于Ruby学习的笔记,这些笔记可能涵盖了Ruby的基础概念、核心特性以及进阶话题。在Ruby的学习过程中,理解和掌握以下几个关键知识点至关重要: 1. **面向对象编程...
2. **方法与块(Methods and Blocks)**:Ruby中的方法是用来封装代码的结构,可以被对象调用执行特定任务。块是Ruby的另一大特色,类似于匿名函数,通常用`do...end`或`{...}`表示,常用于迭代和回调。 3. **变量...
了解如何定义和调用方法,以及如何使用块(Blocks)和 Proc 对象,将有助于你编写更复杂的程序。 类和模块是Ruby OOP的关键部分。类是创建对象的蓝图,它们定义了对象的属性(也称为实例变量)和行为(方法)。模块...
Ruby 以其简洁、易读的语法和对开发者友好的特性闻名,比如面向对象编程、块(blocks)、元编程等。 在深入讨论之前,让我们先了解一下 Ruby on Rails 的基本概念: 1. **MVC架构**:Rails 遵循 Model-View-...
"表明你正在进行的项目或学习笔记还没有达到预期的完整状态,这很正常,因为学习和开发往往需要时间来完善。 标签"Ruby"则强调了这个项目的核心语言是Ruby,它是Rails的基础。Ruby语言以其简洁、清晰的语法和对...