Ruby 如何将此if条件转换为除非?
这没有其他部分 如何使用Ruby 如何将此if条件转换为除非?,ruby,Ruby,这没有其他部分 如何使用除非写入上述if条件 我问这个问题是因为这个lint错误: 使用guard子句,而不是将代码包装在条件表达式中 OP要求修改一个班轮: 伪代码: unless array.present? return else puts "hello" end 因此: something unless condition 一艘班轮: puts "hello" unless !array.present? 不过,我建议: puts "hello" unless !array
除非写入上述if
条件
我问这个问题是因为这个lint错误:
使用guard子句,而不是将代码包装在条件表达式中
OP要求修改一个班轮:
伪代码:
unless array.present?
return
else
puts "hello"
end
因此:
something unless condition
一艘班轮:
puts "hello" unless !array.present?
不过,我建议:
puts "hello" unless !array.present?
没有理由。
请记住:,除非是(或者!如果你愿意的话)
,并且只是为了让你的代码更容易阅读
在表达式中使用除非会非常尴尬,因为您现在正在将实际工作转移到else
语句中
puts "hello" if array.present?
…如果您坚持使用否定的if
,这不会使您的代码更易于阅读:
unless array.present?
return
else
puts "hello"
end
除非这里有,否则不要使用。
你会失去可读性,而实际上什么都得不到。关于:
我问这个问题是因为这个皮棉错误
使用guard子句,而不是将代码包装在条件表达式中
这意味着:
if !array.present?
return
else
puts "hello"
end
您应该使用:
def foo(array)
if array.present?
puts "hello"
end
end
看
如果这是Rails问题(),您还可以使用:
出现在哪里?
来自哪里?Rails?是的。对不起,忘了提了<代码>数组。当前?
将为真或假。“还有其他部分”与选择if
vs无关,除非
。谢谢,我们可以做一行吗?为一行编辑。参见上文。除非数组为空?
我忘记了代码>在数组之前。现在?
,但是是的,我相信这也行,塞尔吉奥。上面这行如何工作?如果数组存在?如果是真的,它将返回零。如果数组存在?如果为false,则只有它会返回“hello”。是吗?那么旧的if条件行为将与这段代码正好相反,对吗?我希望在array.present?
为真时打印“hello”,然后您可以使用您发布的代码,它已经非常好了。你不需要除非除非!array.present?
==除非array.blank?
@SergioTulentsev.awesome。此外,如果是上述方法调用。我个人倾向于将返回声明作为一种保护条款<代码>返回如果!array.present?
然后继续使用puts“hello”之类的词。我问这个问题是因为这个lint错误使用一个guard子句,而不是将代码包装在一个条件表达式中
@normanbates:你的linter应该是在帮助你,而不是完全妨碍可读代码。我个人认为上述情况很好;在我看来,你的皮棉似乎过于热情了。
def foo(array)
if array.present?
puts "hello"
end
end
def foo(array)
return unless array.present?
puts "hello"
end
def foo(array)
return if array.blank?
puts "hello"
end