51

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?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Kir
  • 7,981
  • 12
  • 52
  • 69

1 Answers1

112
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>
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • Wouldn't it be great if there was an `Array#diff` or something similar? – Artem Kalinchuk Feb 28 '14 at 11:51
  • 8
    if you want both way difference `a - b | b - a` – equivalent8 Jul 22 '16 at 10:13
  • For one-way diff, also note `a -= b`. – Camille Goudeseune Mar 31 '17 at 16:11
  • 4
    Notice that it will only work with unique values, if a = [1,1, 2, 3, 4, 5] you still get the same [3,5] vs the correct [1,3,5] – s1mpl3 Sep 16 '17 at 22:18
  • 2
    @s1mpl3 : very well noted, `[ 1, 1 ] - [ 1] => [] ` ; it does not look a precise definition of difference for arrays; but how do you give a proper definition of it? What do you call "correct"? – ribamar Feb 19 '18 at 16:04
  • @ribamar Seems like it converts arrays to sets, gets the difference and returns the casted array back. This is the reason we don't have array difference in python. If we are sure of no duplicates, python equivalent of this seems: `list (set(a) - set(b))` – krozaine Jul 10 '18 at 06:00
  • @krozaine: no, it doesn't convert to sets (it would make `Array` to require 'set', which is not a basic ruby structure). I still find more useful to have one weaker definition than defaulting to "if I don't understand the user, user doesn't know what is doing" style of python. In ruby case, even if removing the duplicates was a decision not obvious to understand, still provides the guarantee of returning elements in order -- what doesn't necessarily happen in the case of converting to sets (beyond guaranteeing not wasting time with the conversions themselves). – ribamar Jul 10 '18 at 14:38
  • 3
    in ruby 2.6 we have #difference method https://ruby-doc.org/core-2.6/Array.html#method-i-difference – Roman Feb 23 '20 at 11:33