could anyone by chance give me a working example of the .uniq! method?
i’ve been trying all day. any help would be much appreciated!
jon
could anyone by chance give me a working example of the .uniq! method?
i’ve been trying all day. any help would be much appreciated!
jon
found this in the API docs:
http://www.rubycentral.com/ref/ref_c_array.html#uniq_oh
make sure you’re using it on an array, and remember that if no
duplicates are found, the result is nil.
dorian
Dorian M. wrote:
i’ve been trying all day. any help would be much appreciated!
irb(main):001:0> a = [ 1, 2, 3, 3, 4, 5]
=> [1, 2, 3, 3, 4, 5]
irb(main):002:0> a.uniq
=> [1, 2, 3, 4, 5]
irb(main):003:0> a
=> [1, 2, 3, 3, 4, 5]
irb(main):004:0> a.uniq!
=> [1, 2, 3, 4, 5]
irb(main):005:0> a
=> [1, 2, 3, 4, 5]
irb(main):006:0> a.uniq!
=> nil
Ray
I missed an important bit
=> [1, 2, 3, 3, 4, 5]
irb(main):004:0> a.uniq!
=> [1, 2, 3, 4, 5]
irb(main):005:0> a
=> [1, 2, 3, 4, 5]
irb(main):006:0> a.uniq!
=> nil
irb(main):007:0> a
=> [1, 2, 3, 4, 5]
Ray
On 3/28/06, Ray B. [email protected] wrote:
=> [1, 2, 3, 4, 5]
Ray
Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails
This is exactly according to the documentation. compact and compact!
work
the same way-
Returns a new array by removing duplicate values in _self_.
a = [ "a", "a", "b", "b", "c" ]
a.uniq #=> ["a", "b", "c"]
Removes duplicate elements from _self_. 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
Regards,
Nick
2006/3/27, Jon [email protected]:
could anyone by chance give me a working example of the .uniq! method?
i’ve been trying all day. any help would be much appreciated!
array = %w(a a)
puts array
[“a”, “b”]
array.uniq!
puts array
[“a”]
#uniq! makes the receiver keep unique values. Values are compared
using #== (or is it #equal?). #uniq! is equivalent to this loop:
temp = Array.new
%w(a a).each do |value|
temp << value unless temp.include?(value)
end
Of course, this loop returns a NEW array, whereas #uniq! changes the
receiver (notice ! at the end ?)
Hope that helps !
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs