使用if的Void值表达式ruby
我有一段代码:使用if的Void值表达式ruby,ruby,Ruby,我有一段代码: def load_logged_user hero, method = if session[:hero] return Hero.find_by(id: session[:hero]), :session elsif cookies.permanent.signed[:token] return hero_from_cookie, :cookie
def load_logged_user
hero, method = if session[:hero]
return Hero.find_by(id: session[:hero]), :session
elsif cookies.permanent.signed[:token]
return hero_from_cookie, :cookie
end
@_logged_user = { hero: hero, method: method } if hero
end
我在if的
end
行上遇到了一个void值表达式
错误。我从文档中了解到ruby中的所有内容都被视为lambdas,所以我的问题是:为什么这不起作用?我遗漏了什么?只需从代码中删除返回的:
def load_logged_user
hero, method = if session[:hero]
[Hero.find_by(id: session[:hero]), :session]
elsif cookies.permanent.signed[:token]
[hero_from_cookie, :cookie]
end
@_logged_user = { hero: hero, method: method } if hero
end
使用return
将代码从函数中取出,这可能不是您想要做的
请记住,由于您的代码中没有else
子句,因此可能不会发生赋值,并且hero
和method
都将nil
您需要告诉ruby如果hero为nil会发生什么,所以请像这样重写您的代码
@_logged_user = hero.nil? ? false : { hero: hero, method: method }
谢谢,但是我不能只返回两个值而不返回,对吗?我需要将它们包装在散列中吗?您可以返回任意数量的数据,只需将它们包装在数组中,就像[hero\u from_cookie,:cookie]
@Bahaïka根据Ruby文档,方法有返回值,但如果表达式有结果值,则返回。这种区别可能有助于理解错误的原因。感谢@Stefan提供这些信息:我确实了解返回
和结果