Ruby | Array Difference (-) function

Array#-() is a Array class method which performs set difference operation by removing the similar elements of the two array.

Syntax: Array.-()

Parameter: Arrays for performing the concatenation operation.



Return: New arrays by removing the same elements of the two arrays.

Example #1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for -() method
# showing concatenate operation
  
# declaring array
a = [18, 22, 33, 4, 5, 6]
  
# declaring array
b = [5, 4, 22, 1, 88, 9]
  
# declaring array
c = [18, 22, 33, 40, 50, 6]
  
# differencing arrays
puts "difference of a and b : #{a - b}\n\n"
  
# differencing arrays
puts "difference of a and c : #{a - c}\n\n"
  
# differencing arrays
puts "difference of b and c : #{b - c}\n\n"

chevron_right


Output :

difference of a and b : [18, 33, 6]

difference of a and c : [4, 5]

difference of b and c : [5, 4, 1, 88, 9]

Example #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby code for -() method
# showing concatenate operation
  
# declaring array
a = ["abc", "xyz", "dog"]
  
# declaring array
b = ["cow", "cat", "dog"]
  
# declaring array
c = ["cat", "1", "dog"]
  
# differencing arrays
puts "difference of a and b : #{a - b}\n\n"
  
# differencing arrays
puts "difference of a and c : #{a - c}\n\n"
  
# differencing arrays
puts "difference of b and c : #{b - c}\n\n"

chevron_right


Output :

difference of a and b : ["abc", "xyz"]

difference of a and c : ["abc", "xyz"]

difference of b and c : ["cow"]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.