我刚开始使用 Ruby,我个人认为以下内容违反了“最小意外原则”。也就是说,引用自 the documentation ,那个独特的! “从 self 中删除重复元素。如果未进行任何更改(即未找到重复元素),则返回 nil。”
谁能解释一下,这对我来说似乎完全违反直觉?这意味着不是能够通过附加 .uniq 来编写下面的一行代码!为了结束第一行,我不得不写以下两行:
hooks = IO.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/)
hooks = hooks.uniq
或者我是否遗漏了一些更好的方法?
编辑:
我明白 uniq 了!修改其操作数。我希望这里的问题能更好地说明:
hooks = IO.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/)
puts hooks.length #50
puts hooks.uniq!.length #undefined method `length' for nil:NilClass
我主张uniq的方式!作品使它完全没有意义和无用。当然,就我而言,正如所指出的,我可以将 .uniq 附加到第一行。但是稍后在同一个程序中,我将元素推到循环内的另一个数组中。然后,在循环下,我想对数组进行“去重”,但我不敢写'hooks_tested.uniq!'因为它可以返回零;相反,我必须写 hooks_tested = hooks_tested.uniq
事实上,我认为这是一个特别严重的错误特征,因为众所周知的原则是,在设计返回数组的方法时,应该始终至少返回一个空数组,而不是 nil
最佳答案
这是因为 uniq!
修改了 self
,如果 uniq!
会返回一个值,您将无法知道是否发生了变化实际发生在原始对象中。
var = %w(green green yellow)
if var.uniq!
# the array contained duplicate entries
else
# nothing changed
end
在你的代码中你可以简单地写
hooks = IO.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/)
hooks.uniq!
# here hooks is already changed
如果你需要返回 hook 的值可能是因为它是最后一个方法语句就这样做
def method
hooks = IO.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/)
hooks.uniq
end
否则
def method
hooks = IO.read(wt_hooks_impl_file).scan(/wt_rt_00\w{2}/)
hooks.uniq!
hooks
end
关于ruby - 为什么 uniq!如果没有重复则返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2102252/