Remove duplicate elements from array in Ruby

Remove duplicate elements from array in Ruby

Asked on December 20, 2018 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    Try this code: 

    array = array.uniq
    
    

    The  uniq method removes all duplicate elements and retains all elements in the array only on  Ruby language.

    Answered on December 20, 2018.
    Add Comment

    Developer can Use return the intersection and delete duplicates;

    a = [1,1,2,3]
    a & a
    

    Answered on December 20, 2018.
    Add Comment

    Alternative solution for Remove duplicate elements :

    uniq method:

    array.uniq # => [1, 2, 4, 5, 6, 7, 8]
    
    

    The might  be useful to know the uniq method takes a block, Example:

    ["bucket1:file1", "bucket2:file1", "bucket3:file2", "bucket4:file2"]
    
    

    They unique files we can find some element:

    a.uniq { |f| f[/\d+$/] }.map { |p| p.split(':').last }
    
    

    Answered on December 20, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.