首页 > 解决方案 > 比较两个数组 Ruby 2.0

问题描述

我是学习 ruby​​ 的新手,创建了两个数组。我正在尝试将数组 1 的每个元素与数组 2 进行比较,并打印数组 1 中不存在的元素和数组 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

标签: arraysruby

解决方案


你只需要减去它们:

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

array_1 - array_2
=> [1, 2]

array_2 - array_1
=> [5, 6]

推荐阅读