a = [1,2,3]
a.uniq! # nil
a.uniq # [1,2,3]
Why a.uniq! is not [1,2,3] ?
Let me know the reason. Thank you!
a = [1,2,3]
a.uniq! # nil
a.uniq # [1,2,3]
Why a.uniq! is not [1,2,3] ?
Let me know the reason. Thank you!
You need to read the Ruby documentation.
The uniq
method returns a new array by removing duplicate values in self. If no duplicates are found, the same array value is returned.
a = [ "a", "a", "b", "b", "c" ]
a.uniq # => ["a", "b", "c"]
b = [ "a", "b", "c" ]
b.uniq # => ["a", "b", "c"]
The uniq!
method removes duplicate elements from self and returns nil
if no changes are made (that is, no duplicates are found).
a = [ "a", "a", "b", "b", "c" ]
a.uniq! # => ["a", "b", "c"]
b = [ "a", "b", "c" ]
b.uniq! # => nil
most of the methods ending with bang (!) change the variable, while those without it just return the altered variable.
So, if you have something like this:
a = [1, 1, 2, 3]
a.uniq
will return [1, 2, 3]
, but wont alter a
, while a!
will alter a
to be equal to [1, 2, 3]
[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]