Rumen Hristov
Rumen Hristov

Reputation: 887

Ruby code to merge two arrays not working

nums1 = Array[1, 2, 3, 4, 5]
nums2 = Array[5, 6, 7, 8, 9]

def mergeArrays (ar1, ar2)
   result = (ar1 << ar2).flatten!

   require 'pp'
   pp %w(result)
end

As simple as this. I am trying to merge these two arrays and display the result. I am also brand-brand new to Ruby. This is the first function I am writing in this language. Trying to learn here. Also how can I remove the duplicates?

Upvotes: 0

Views: 549

Answers (4)

Josh
Josh

Reputation: 100

What do you mean 'not working'?

Similar questions have been asked here: Array Merge (Union)

You have two options: the pipe operator (a1 | a2) or concatenate-and-uniq ((a1 + a2).uniq).

Also be careful about using <<, this will modify the original variable, concatenating ar2 onto the end of the original ar1.

nums1 = Array[1, 2, 3, 4, 5]
nums2 = Array[5, 6, 7, 8, 9]
result = (nums1<< nums2).flatten!

nums1
=> [1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
nums2 
=> [5, 6, 7, 8, 9]
result
=> [1, 2, 3, 4, 5, 5, 6, 7, 8, 9]

Additionally- just another Ruby tip, you do not need the destructive flatten! with ! versus the regular flatten. The regular flatten method will return a new Array, which you assign to result in your case. flatten! will flatten self in place, altering whatever Array it's called upon, rather than returning a new array.

Upvotes: 3

Kalman
Kalman

Reputation: 8131

nums1 = Array[1, 2, 3, 4, 5]
nums2 = Array[5, 6, 7, 8, 9]

p nums1.concat(nums2).uniq

Upvotes: 1

Dharmesh Rupani
Dharmesh Rupani

Reputation: 1007

You can merge Arrays using '+' operator and you can ignore the duplicated values using .uniq

>> nums1 = Array[1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
>> nums2 = Array[5, 6, 7, 8, 9]
=> [5, 6, 7, 8, 9]

>> def mergeArrays (nums1, nums2)
>> result = (nums1 + nums2).uniq
>> end
=> :mergeArrays

>> mergeArrays(nums1,nums2)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]

Upvotes: 1

David Grayson
David Grayson

Reputation: 87506

It would help if you give example inputs and outputs so we know exactly what you want. When you use the word "merge", I think you actually just want to add the arrays together:

ar1 = [1, 2, 3]
ar2 = [3, 4, 5]
ar3 = ar1 + ar2   # => [1, 2, 3, 3, 4, 5]

Now if you want to remove duplicates, use Array#uniq:

ar4 = ar3.uniq    # => [1, 2, 3, 4, 5]

There is no need to write a method to do any of this since the Ruby Array class already supports it. You should skim through the documentation of the Array class to learn more things you can do with arrays.

Upvotes: 5

Related Questions