是否存在用于not_nil的Ruby或Ruby-ism?零对面?方法?

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)

  • 注意:`present?`需要一个非空字符串.`!"".nil?`返回true,但是``".present?`返回false. (43认同)
  • `false.present?== false``!false.nil?== true` (11认同)
  • 当心2:我还要注意!!用户不区分用户为零和用户为假; 双重用法将这两者混为一谈.所以如果你真的想要确定一个对象是不是nil(意思是,它是:true,false,0,"",除了nil以外的任何东西),你需要使用berkes不喜欢的'丑陋'方法或@Tempus [在下面提出](http://stackoverflow.com/a/4012786/492404)的monkeypatch.当然,在这种情况下,不需要nil*(Rails中的用户),[Samo采取的方法](http://stackoverflow.com/a/4016263/492404)是最不丑的,imo. (9认同)
  • 这个答案是不正确的。false.nil?是假的,而false.present?也是假的! (5认同)
  • 这个答案根本没有回答所提出的问题。这是对这个特定实现问题的答案。 (4认同)

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)

  • 以“?”结尾的方法的期望是它返回一个布尔值。`!!value` 是将任何内容转换为布尔值的经典方法。不完全相同,但在这种情况下,RoR 中的“Object#present?”也很好。 (2认同)

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)

  • 你不需要自己.这将暗示. (3认同)

Chr*_*bek 12

我可以在该!方法的结果上提供 Ruby 式的方法吗nil?

def logged_in?
  user.nil?.!
end
Run Code Online (Sandbox Code Playgroud)

如此深奥,RubyMine IDE 会将其标记为错误。;-)