在 Ruby 中如何在没有开始和结束块的情况下使用 save

我知道开始救援的标准技术

一个人怎么能自己使用救援区呢。

它是如何工作的? 它如何知道正在监视哪些代码?

43398 次浏览

方法“ def”可以作为“ start”语句:

def foo
...
rescue
...
end

你也可以直接拯救:

1 + "str" rescue "EXCEPTION!"

将打印出“例外!”,因为“字符串不能被强制进入 Fixnum”

我经常在 ActiveRecord 验证中使用 def/save 组合:

def create
@person = Person.new(params[:person])
@person.save!
redirect_to @person
rescue ActiveRecord::RecordInvalid
render :action => :new
end

我认为这是非常精简的代码!

例如:

begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end

这里,def作为 begin语句:

def
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end

额外的好处! 你也可以用其他类型的积木来做这个。例如:

[1, 2, 3].each do |i|
if i == 2
raise
else
puts i
end
rescue
puts 'got an exception'
end

irb中输出:

1
got an exception
3
=> [1, 2, 3]