Array.reject!(&:empty?)删除非空对象

sma*_*591 1 ruby arrays

我无法弄清楚为什么,但在使用时reject!(&:empty?),非空对象被删除.

例:

["example"].reject!(&:empty?)
Run Code Online (Sandbox Code Playgroud)

退货nil.然而,

["example", ""].reject!(&:empty?)
Run Code Online (Sandbox Code Playgroud)

["example"]像它应该的那样返回.

为什么?

Uri*_*ssi 5

文档:

相当于#delete_if,从块中计算为true的self中删除元素,但如果没有进行任何更改则返回nil.

如果你想使用数组的结果(并且对更改数组不太感兴趣- 请reject改用:

["example"].reject(&:empty?)
# => ["example"]
["example", ""].reject(&:empty?)
# => ["example"]
Run Code Online (Sandbox Code Playgroud)