redo,retry,next,break,return,begin
redo
只是重新执行当前循环。具体的解释只对块内部的代码执行循环,不关注块外部的代码,下面的代码中
#块内部代码
puts i
i+=1
redo if i==2
#块外部代码
ary.each do |i|
end
#代码示例1
ary=[1,2,3]
ary.each do |i|
puts i
i+=1
redo if i==2
end
#1,2,2,3
#代码示例2
for i in 0..5
puts "Value of local variable is #{i}" if i<2
redo
end
#会有无限循环的
Value of local variable is 0
Value of local variable is 0
....
#代码示例3
("a".."f").each do |i|
puts "Value: #{i}"
redo if i > "c"
end
#会无限循环d,结果为 a,b,c,d,d,d,d....
retry
http://ruby-doc.org/core-2.1.3/doc/syntax/exceptions_rdoc.html
Inside a rescue block is the only valid location for retry, all other uses will raise a SyntaxError.
If you wish to retry a block iteration use redo.
就是说retry只有在rescue代码中是有效的,如果出现在其他地方会出现语法错误。retry是从begin代码开始,把代码重新执行一遍。
begin
#这段代码抛出的异常将被下面的rescue子句捕获
rescue
#这个块将捕获所有类型的异常
retry #这将把控制移到begin的开头
end
next
跳出遍历
#代码示例
for i in 0..5
if i < 2 then
next
end
puts "Value of local variable is #{i}"
end
#result
Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
break
#代码示例
for i in 0..5
if i > 2 then
break
end
puts "局部变量的值为 #{i}"
end
#result
局部变量的值为 0
局部变量的值为 1
局部变量的值为 2
return
#一般情况下,返回方法的最后一段语句
def demo
"hello world"
end
p demo #"hello world"
#如果出现return 返回return后面的值
def demo
return "hello world"
end
p demo #"hello world"
#如果执行了return语句,之后的代码不执行,所以就有了下面的常用法
def demo
x = 10
return "hello" if x==10
"hello world"
end
p demo # "hello"
返回值和打印值
#返回值
def demo
return "hello world"
end
demo #返回值"hello world"
#打印值
def demo
puts "hello world"
end
demo #打印值是"hello world",返回值是nil,就是不存在返回值
#存在返回值可以记性链式操作,如果没有返回值则不行
begin
1.使用在rescue中,结尾必须结合end,在方法中begin可以省略
#begin和end成对出现
def demo
begin
1/0
rescue ZeroDivisionError => e
p e
end #end必须添加
end
#方法中可以省略begin
def demo
1/0
rescue ZeroDivision => e
p e
end
2.BEGIN{}和END{}块中
#BEGIN{}在程序运行之前被调用,END{}在程序结束之后被调用
BEGIN{ puts "begin" }
END{ puts "end" }
puts "this the demo"
#执行结果如下
begin
this the demo
end
3.begin ..end类似一段代码块,顺序执行,不必像pro一样只用call调用
#code sample
class Demo
attr_accessor :name
def demo
@name ||= begin
"hello world"
end
end
end
obj = Demo.new
p obj.demo #"hello world"