我在我的代码中有以下逻辑:
if !@players.include?(p.name)
...
end
@players是一个数组。有什么方法可以让我避免!?
理想情况下,这个代码片段应该是:
if @players.does_not_include?(p.name)
...
end
我在我的代码中有以下逻辑:
if !@players.include?(p.name)
...
end
@players是一个数组。有什么方法可以让我避免!?
理想情况下,这个代码片段应该是:
if @players.does_not_include?(p.name)
...
end
当前回答
if @players.exclude?(p.name)
...
end
ActiveSupport添加排除?数组,散列和字符串。这不是纯Ruby,但是被很多Ruby爱好者使用。
来源:活动支持核心扩展(Rails指南)
其他回答
试试这个,它是纯Ruby,所以不需要添加任何外围框架
if @players.include?(p.name) == false do
...
end
我在类似的逻辑中挣扎了几天,在查看了几个论坛和问答板后,结果发现解决方案实际上非常简单。
给你:
unless @players.include?(p.name)
...
end
您可以查看Ruby Style Guide以获得有关类似技术的更多信息。
如果你对!-操作符的反对主要是它需要放在你的检查符前面,这会破坏你的输入流程,那么就有。!方法。你只需要把它放在check之后来反转布尔值:
if @players.include?(p.name).!
使用,除非:
unless @players.include?(p.name) do
...
end
使用unless可以用于包含单个include的语句?子句,但是,例如,当你需要检查一些东西是否包含在一个数组中,而不是另一个数组中,使用include?排除?友好多了。
if @players.include? && @spectators.exclude? do
....
end
但是正如dizzy42上面所说的,exclude的使用?需要ActiveSupport这样