gpt4 book ai didi

Ruby - 返回 false 除非值是 true 在这种情况下返回值

转载 作者:数据小太阳 更新时间:2023-10-29 07:30:13 24 4
gpt4 key购买 nike

如果 a = falseb = 2 是否有一种简洁的方法来实现这一点?仅使用 return a unless b 返回“nil”而不是“2”。

我有

def checkit
return a unless b
b
end

这个语句会调用 b 两次吗?

一个真实的案例是:

def current_user
@current_user ||= authenticate_user
end

def authenticate_user
head :unauthorized unless authenticate_from_cookie
end

def authenticate_from_cookie
.
if user && secure_compare(user.cookie, cookie)
return user
else
return nil
end
end

最佳答案

试试这个:

 ( b == true ) ? a : false

其中 a 是您需要返回的值

关于Ruby - 返回 false 除非值是 true 在这种情况下返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22563319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com