【问题标题】:Ruby - return false unless a value is true in which case return the valueRuby - 除非值为真,否则返回假,在这种情况下返回值
【发布时间】:2014-03-21 15:46:45
【问题描述】:

如果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

【问题讨论】:

  • 代码和语句对我来说是矛盾的.. :( 你在哪里写 If a = falseb = 2 在你的代码中?

标签: ruby return conditional-statements


【解决方案1】:

试试这个:

 ( b == true ) ? a : false

其中 a 是您需要返回的值

【讨论】:

    【解决方案2】:

    我不知道你为什么将false 存储在变量a 中,所以我省略了。据我了解,您希望将值传递给方法checkit,如果其布尔值为true(这意味着除值nilfalse 之外的所有值),则该方法应返回该值,否则返回该值.在这种情况下,只需使用这个:

    def checkit(value)
      value || false
    end
    
    checkit(1)       # => 1
    checkit(false)   # => false
    checkit('value') # => "value"
    checkit(nil)     # => false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 2016-05-03
      • 2013-06-14
      • 2021-12-31
      • 2017-04-01
      • 1970-01-01
      • 2016-03-02
      相关资源
      最近更新 更多