0

I'm new to studying ruby ​​and have created two arrays. I'm trying to compare each element of array 1 with array 2 and print the ones that don't exist in array 1 and what doesn't exist in array 2.

  **#localarraydb**
    bdlocal = CTrunk.find_by_sql('select phone_number from phones_trunks;')


    connect = PG.connect(:hostaddr => @servers[0], :port => 5432, :dbname => "mydb", :user => "myuser", :connect_timeout => 90)
    getdata = connect.exec("select name,active,phone_number from phones_trunks;")
    array = []


    getdata.each do |re|
    array << re.values[2]
    puts array
end


**#Local Array DB retrive each item from db**
    bdlocal.each do |compare|
    puts "Server 11:#{array[2]}\n Server Local:#{compare.phone_number}"

 if compare == getdata then
        puts "equals"
    else
    puts "different #{here show diferrence"
    end
end
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • Maybe this is a good start: https://stackoverflow.com/questions/11238256/how-to-do-sane-set-difference-in-ruby – Druckles Oct 04 '19 at 12:16

2 Answers2

0

You just need to subtract them:

array_1 = [1, 2, 3, 4]
array_2 = [3, 4, 5, 6]

array_1 - array_2
=> [1, 2]

array_2 - array_1
=> [5, 6]
Mark
  • 6,112
  • 4
  • 21
  • 46
  • i using strings from database, have a method to puts only not present items? see my code array.each do |x| if (arrlocal.include?(x)) puts "#{x}" end using this i retrieve all is present but not show is not present can help me – Victor Coelho Oct 04 '19 at 11:53
  • But please take care of these cases. `[5, 5, 5, 5] - [5, 5] = []` and `[1,2]-[1,2,3] => []. But [1,2,3]-[1,2] => [3]`. – Ajay Barot Oct 04 '19 at 12:15
  • @VictorCoelho - if your arrays are called `arrlocal` and `arr2` then you need to do – Mark Oct 04 '19 at 12:15
  • puts "Things in arrlocal but not in arr2 are: #{arrlocal - arr2}" puts "Things in arr2 but not in arrlocal are #{arr2 - arrlocal}" puts "Things in one array but not another are #{(arr2 -arrlocal) + (arrlocal - arr2)}" – Mark Oct 04 '19 at 12:16
0

I don't completely understand your objection to Mark's answer. But perhaps using the 'filter' method could help?

array_1 = [1, 2, 3, 4]
array_2 = [3, 4, 5, 6]

To return elements FOUND in both arrays:

array_1.filter {|item| array_2.include?(item)}
=> [3, 4]

To return elements NOT FOUND in both arrays:

array_1.filter {|item| !array_2.include?(item)}
=> [1, 2]

I'm not sure if needed, but Ruby has a nifty little method called split which, well, splits a string into items in an array. Could help?

text = 'hello there i am a boring string of text'

To return an array of words:

text.split(' ')
=> ["hello", "there", "i", "am", "a", "boring", "string", "of", "text"]

Best of luck!

yeniv
  • 93
  • 8