Skip to content

Instantly share code, notes, and snippets.

@zumbalogy
Created August 3, 2014 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zumbalogy/6ff391c14d8c921bd79d to your computer and use it in GitHub Desktop.
Save zumbalogy/6ff391c14d8c921bd79d to your computer and use it in GitHub Desktop.
uniq in ruby is funny stuff
[1,2,3].permutation {|v| p v if v.first.odd?}
[1, 2, 3]
[1, 3, 2]
[3, 1, 2]
[3, 2, 1]
# => [1, 2, 3]
[1,1,2,2,3,3].uniq
# => [1, 2, 3]
[1,1,2,2,3,3].uniq &:odd?
# => [1, 2] # this is because true and false are two unique values
[1,1,2,2,3,3].uniq &:even?
# => [1, 2]
[1,1,2,2,3,3].uniq &:to_s
# => [1, 2, 3]
[1,1,2,2,3,3].uniq {|v| p v}
1
1
2
2
3
3
# => [1, 2, 3]
[1,1,2,2,3,3].uniq {|v| v + 5}
# => [1, 2, 3]
[1,1,2,2,3,3].uniq {|v| v.even? ? v + 1 : v}
# => [1, 2]
[1,1,2,2,3,3].uniq {|v| v.odd? ? v + 1 : v}
# => [1, 3]
[1,1,2,2,3,3,4,4].uniq {|v| v.odd? ? v + 1 : v}
# => [1, 3]
[1,1,2,2,3,3,4,4].uniq {|v| v.even? ? v + 1 : v}
# => [1, 2, 4]
[1,2,3].permutation
# => #<Enumerator: [1, 2, 3]:permutation>
[1,2,3].permutation.to_a
# => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[1,2,3].permutation.to_a.uniq
# => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[1,2,3].permutation.to_a.uniq &:last
# => [[1, 2, 3], [1, 3, 2], [2, 3, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment