ruby - what is the difference between uniq! and uniq
本问题已经有最佳答案,请猛点这里访问。
1 2 3 | a = [1,2,3] a.uniq! # nil a.uniq # [1,2,3] |
为什么啊!不是[1,2,3]?
告诉我原因。谢谢您!
您需要阅读Ruby文档。
1 2 3 4 5 | a = ["a","a","b","b","c" ] a.uniq # => ["a","b","c"] b = ["a","b","c" ] b.uniq # => ["a","b","c"] |
1 2 3 4 5 | a = ["a","a","b","b","c" ] a.uniq! # => ["a","b","c"] b = ["a","b","c" ] b.uniq! # => nil |
大多数以bang(!)结尾的方法更改变量,而没有它的则返回更改后的变量。
所以,如果你有这样的东西:
1 | a = [1, 1, 2, 3] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [1] pry(main)> a = [1,1,2,3] => [1, 1, 2, 3] [2] pry(main)> a.uniq => [1, 2, 3] [3] pry(main)> a => [1, 1, 2, 3] [4] pry(main)> a.uniq! => [1, 2, 3] [5] pry(main)> a => [1, 2, 3] [6] pry(main)> a.uniq! => nil [7] pry(main)> a => [1, 2, 3] |