如何在没有`return`的情况下返回一个值

时间:2015-07-07 14:32:20

标签: ruby-on-rails ruby

如果没有return类似设计的authenticate!方法,我该怎么办?

class GroupsController < ApplicationController
  def create
    authenticate! # After here, the code below will not be excuted.
    @group = Group.create(group_params)
    redirect_to groups_path
  end
end

我想知道如何做到这一点。

2 个答案:

答案 0 :(得分:1)

设计authenticate!在失败时不会返回,如果用户未经过身份验证,它实际上会抛出异常。异常将在整个调用链中传播,直到它遇到匹配的rescue语句。 Rails框架非常智能,它可以挽救此类异常并将特定异常转换为相应的HTTP状态代码,例如,ActiveRecord::RecordNotFound将转换为404

这是从深度调用层次结构返回的常见编程技巧。

def a
  raise "ha"
end
def b
  puts "calling a"
  a
  not executed
end
def c
  b rescue nil
end

c #=> calling a

而红宝石提供的catch/throw就是为了这种更深层的跳跃。

catch(:ret) do
  (1..5).each do |i|
    (1..5).each do |j|
      puts i * j
      throw :ret if i * j > 3
    end
  end
end

答案 1 :(得分:0)

您是否只是在不使用关键字'return'来询问如何返回?

Ruby会自动从方法的最后一行返回结果,如果这就是你的意思。但它与使用关键字'return'相同。