【问题标题】:Compare two arrays Ruby 2.0比较两个数组 Ruby 2.0
【发布时间】:2020-02-02 17:46:10
【问题描述】:

我是学习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

【问题讨论】:

标签: arrays ruby


【解决方案1】:

你只需要减去它们:

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

array_1 - array_2
=> [1, 2]

array_2 - array_1
=> [5, 6]

【讨论】:

  • 我使用数据库中的字符串,有一种方法可以只放置不存在的项目吗?看我的代码 array.each 做 |x| if (arrlocal.include?(x)) puts "#{x}" end using this i retrieve all is present but not show is not present 可以帮助我
  • 但是请注意这些情况。 [5, 5, 5, 5] - [5, 5] = [][1,2]-[1,2,3] =&gt; []. But [1,2,3]-[1,2] =&gt; [3].
  • @VictorCoelho - 如果你的数组被称为 arrlocalarr2 那么你需要这样做
  • puts "在 arrlocal 但不在 arr2 中的东西是:#{arrlocal - arr2}" puts "在 arr2 中但不在 arrlocal 中的东西是 #{arr2 - arrlocal}" 将 "东西放在一个数组中,但是不是另一个是 #{(arr2 -arrlocal) + (arrlocal - arr2)}"
【解决方案2】:

我不完全理解您对马克回答的反对意见。但也许使用“过滤器”方法会有所帮助?

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

返回在两个数组中找到的元素:

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

返回两个数组中都没有找到的元素:

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

我不确定是否需要,但 Ruby 有一个漂亮的小方法,称为 split,它可以将字符串拆分为数组中的项目。可以帮忙吗?

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

返回一个单词数组:

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

祝你好运!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 2021-09-30
    • 2021-01-24
    相关资源
    最近更新 更多