Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - what is the difference between uniq! and uniq [duplicate]

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!

like image 881
Yonggoo Noh Avatar asked Nov 25 '15 18:11

Yonggoo Noh


People also ask

What is. uniq in Ruby?

uniq is a Ruby method that returns a new array by removing duplicate elements or values of the array. The array is traversed in order and the first occurrence is kept.


2 Answers

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
like image 190
valdeci Avatar answered Oct 21 '22 10:10

valdeci


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]
like image 42
bosskovic Avatar answered Oct 21 '22 10:10

bosskovic