5
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!

Yonggoo Noh
  • 1,486
  • 3
  • 16
  • 34
  • [http://ruby-doc.org/core-2.2.0/Array.html](http://ruby-doc.org/core-2.2.0/Array.html) – resueman Nov 25 '15 at 18:07
  • Welcome to Stack Overflow. Please don't use Stack Overflow as a replacement for reading the documentation and doing your research. Please read "[ask]" and http://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users – the Tin Man Nov 25 '15 at 18:31

2 Answers2

8

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
valdeci
  • 8,287
  • 4
  • 39
  • 57
5

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]
bosskovic
  • 1,958
  • 1
  • 12
  • 27
  • 3
    It is worth noting that, while the bang is used to denote "dangerous" methods in ruby as @bosskovic said, you can't always safely assume this is the case. For instance, a number of active record methods (such as .save! and .create!) use the bang to denote that they will raise an exception if they fail instead of returning false. It's safest to look them up on a method-by-method basis, as there is no enforcing that either of these conventions are followed. – ConnorCMcKee Nov 25 '15 at 18:12
  • This answer does not explain the `nil`. – Nawaz Feb 12 '18 at 08:14