Skip to content

Instantly share code, notes, and snippets.

@covard
Last active December 19, 2015 05:29
Show Gist options
  • Save covard/5904585 to your computer and use it in GitHub Desktop.
Save covard/5904585 to your computer and use it in GitHub Desktop.
How to diff two arrays in ruby and get just the values that are different between the two arrays.
first_hdr = ["hello", "world"]
second_hdr = ["hello", "world", "!"]
new_columns = second_hdr - first_hdr # changed the code to use the way Morgan found, seems more ruby to me ;)
# output
# new_columns => ["!"]
# can also use reject! and that will reject on the second_hdr so then it would be
# second_hdr => ["!"]
# Happy Rubying =)
# Also see Morgan's comments below. I actully like his method better. He is a much beter developer than me and thinks of even
# better ways of doing things.
@localstatic
Copy link

For the first use case (the one without "reject!") you can also do:

second_hdr - first_hdr

e.g.:

new_columns = second_hdr - first_hdr

# output
# new_columns => ["!"]

# you can also use second_hdr -= first_hdr as an equivalent to your reject! example
second_hdr -= first_hdr

# output
# second_hdr => ["!"]

@covard
Copy link
Author

covard commented Jul 1, 2013

Nice I like that way better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment