Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get difference of arrays in Ruby [duplicate]

Tags:

arrays

ruby

Possible Duplicate:
diff a ruby string or array

I have an old array: [1, 2, 3, 4, 5], and new: [1, 2, 4, 6]

How to get difference with Ruby: that 5, 3 was removed and 6 was added?

like image 441
Kir Avatar asked Aug 21 '11 16:08

Kir


People also ask

How do you check if there are duplicates in an array Ruby?

select { array. count } is a nested loop, you're doing an O(n^2) complex algorithm for something which can be done in O(n). You're right, to solve this Skizit's question we can use in O(n); but in order to find out which elements are duplicated an O(n^2) algo is the only way I can think of so far.

How do you compare two arrays in Ruby?

Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.

What is .first in Ruby?

first is a property of an array in Ruby that returns the first element of an array. If the array is empty, it returns nil. array. first accesses the first element of the array, i.e., the element at index 0 .

What is the difference between array and hash in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements.


1 Answers

irb(main):001:0> a = [1, 2, 3, 4, 5] => [1, 2, 3, 4, 5] irb(main):002:0> b = [1, 2, 4, 6] => [1, 2, 4, 6] irb(main):003:0> a - b => [3, 5] irb(main):005:0> b - a => [6] irb(main):006:0> 
like image 65
Dogbert Avatar answered Oct 21 '22 12:10

Dogbert