Ruby 比“红宝石”更漂亮;!当前用户。无;?

Ruby 比“红宝石”更漂亮;!当前用户。无;?,ruby,Ruby,好的,我是绿色的,但是下面的def看起来是双负y def signed_in? !current_user.nil? #the current user is not...um...not end 因为我的病人导师M.Hartl在治疗中使用了它。我得相信它吱吱作响,但是 说“当前用户是”的东西不是更干净吗 def signed_in? current_user current_user.present? current_user.any? !!current_user e

好的,我是绿色的,但是下面的def看起来是双负y

def signed_in?
  !current_user.nil?  #the current user is not...um...not
end
因为我的病人导师M.Hartl在治疗中使用了它。我得相信它吱吱作响,但是

说“当前用户是”的东西不是更干净吗

def signed_in?
  current_user
  current_user.present?
  current_user.any?
  !!current_user
end

爆炸的好处是什么?

在该示例中,您不关心用户是谁。您只想知道一个用户,任何用户,已经登录。如果是,您将显示登录用户的链接

当前用户.nil?
是一个布尔值。如果用户已登录,则为false。前面的砰砰声使它反转,所以
!如果有任何用户登录,当前用户.nil?
将为true,否则为false

你能想出另一种同样简洁的方法来实现这一点吗,不多也不少?

你可以:

current_user          | nil    | false  | true  | ""    | []    | [nil] | [0]  
-----------------------------------------------------------------------------------
current_user          | nil    | false  | true  | ""    | []    | [nil] | [0]
!current_user.nil?    | false  | true   | true  | true  | true  | true  | true
!!current_user        | false  | false  | true  | true  | true  | true  | true
current_user.present? | false  | false  | true  | false | false | true  | true
current_user.any?     | error  | error  | error | error | false | false | true
def signed_in?
  current_user
end
如果您能忍受它不是从方法返回的布尔值。如果当前用户为nil
signed\u in?
将在If语句中使用时计算为false。检查零?没有必要,我想这是风格的问题

或者在您的呼叫代码中,您可以:

if current_user
  # do stuff
end

并且去掉多余的方法

为什么不在你给出的选项中选一个你最喜欢的呢?这最终是非常主观的。谢谢你的链接编辑安德鲁。我很懒。但是我给你的所有选择都有效吗?还是真的有很好的理由使用爆炸/双重否定?谢谢迭戈,我本质上问的问题和你最后问的差不多,有没有一种更简洁、也许更易读的方法,可以在没有漏洞的情况下完全做到这一点?不,我不认为有。任何现在呢?它们不是通用的,它们取决于类型。无对每个物体都有效,这是有道理的。谢谢迭戈!谢谢@sawa这正是我需要看到的。你错过了一个经常让人绊倒的案例,那就是
any?
[nil,false]。any?#=>错误