关于ruby:uniq! 和uniq 有什么区别!

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文档。

uniq方法通过删除自身的重复值来返回一个新数组。如果找不到重复项,则返回相同的数组值。

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"]

uniq!方法从self中删除重复的元素,如果没有进行任何更改(即没有找到重复的元素),则返回nil

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]

a.uniq返回[1, 2, 3]但不改变aa!a改为等于[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]