ber*_*kes 81 ruby null ruby-on-rails
我没有Ruby经验,所以我的代码感觉"丑陋"而不是惯用语:
def logged_in?
!user.nil?
end
Run Code Online (Sandbox Code Playgroud)
我宁愿有类似的东西
def logged_in?
user.not_nil?
end
Run Code Online (Sandbox Code Playgroud)
但找不到这样一种对立的方法 nil?
lwe*_*lwe 49
当你使用ActiveSupport时,有user.present? http://api.rubyonrails.org/classes/Object.html#method-i-present%3F,只检查非零,为什么不使用
def logged_in?
user # or !!user if you really want boolean's
end
Run Code Online (Sandbox Code Playgroud)
Sam*_*amo 48
你似乎过分担心布尔人.
def logged_in?
user
end
Run Code Online (Sandbox Code Playgroud)
如果用户是nil,那么logged_in?将返回"假"值.否则,它将返回一个对象.在Ruby中,我们不需要返回true或false,因为我们在JavaScript中有"truthy"和"falsey"值.
更新
如果您正在使用Rails,则可以使用以下present?方法更好地阅读:
def logged_in?
user.present?
end
Run Code Online (Sandbox Code Playgroud)
A F*_*kly 18
请注意其他答案,present?作为您问题的答案.
present?与blank?轨道相反.
present?检查是否有有意义的值.这些东西可能无法present?检查:
"".present? # false
" ".present? # false
[].present? # false
false.present? # false
YourActiveRecordModel.where("false = true").present? # false
Run Code Online (Sandbox Code Playgroud)
而!nil?检查给出:
!"".nil? # true
!" ".nil? # true
![].nil? # true
!false.nil? # true
!YourActiveRecordModel.where("false = true").nil? # true
Run Code Online (Sandbox Code Playgroud)
nil?检查对象是否确实存在nil.还有什么:一个空字符串,0,false,什么,是不是nil.
present?是非常有用的,但绝对不是相反的nil?.混淆两者可能会导致意外错误.
对于您的用例present?将起作用,但了解差异总是明智的.
Geo*_*Geo 16
也许这可能是一种方法:
class Object
def not_nil?
!nil?
end
end
Run Code Online (Sandbox Code Playgroud)
Chr*_*bek 12
我可以在该!方法的结果上提供 Ruby 式的方法吗nil??
def logged_in?
user.nil?.!
end
Run Code Online (Sandbox Code Playgroud)
如此深奥,RubyMine IDE 会将其标记为错误。;-)