Ruby入门

http://tech.ddvip.com   2008年01月18日    社区交流

本文详细介绍Ruby入门

1class Employee
2 def initialize(username, age, &block)
3 @username, @age, @block = username, age, block
4 end
5
6 def Display(txt)
7 # 虽然 @block 是个实例变量,但在此处一定要加上大括号
8 print "#{@block.call(txt)}: #@username-#@age"
9 end
10end
11
12emp = Employee.new("proshea", 32){
13 |txt|
14 txt
15}
16emp.Display("context")

  二、BEGIN & END

  BEGIN 块

  BEGIN 块中的代码在所有代码执行之前执行,Ruby 允许设置多个 BEGIN 块并按出现的顺序执行块中的代码。C# 程序员注意下面的代码

BEGIN
{
print "OnInit(object sender, EventArgs args)
"
}
BEGIN
{
print "OnLoad(object sender, EventArgs args)
"
}
print "Running"

  上面的代码看上去很美吧,可惜的是上面的代码段会出现 parse error,正确的代码应该是

BEGIN{
print "OnInit(object sender, EventArgs args)
"
}
BEGIN{
print "OnLoad(object sender, EventArgs args)
"
}
print "Running"

  正如上面的代码段所呈现的,只有当起始大括号和 BEGIN 标识符位于同一行时块内的代码才能得到正确的执行。同时 BEGIN 块也不受任何控制结构的影响,因为只要出现 BEGIN 块就会得到执行并且只执行一次。

1i = 0
2while i < 10
3 # 虽然处理循环结构中,但 BEGIN 块内的代码仍然只执行一次
4 BEGIN{
5 print "OnInit(object sender, EventArgs args)
"
6 }
7 i += 1
8end
9
10if false
11 # BEGIN 完全不受 if 的影响,只要出现 BEGIN 块就会得到执行
12 BEGIN{
13 print "OnLoad(object sender, EventArgs args)
"
14 }
15end
16
17print "Running"

责编:豆豆技术应用

正在加载评论...