在 Ruby 中从另一个数组中减去一个数组 [英] Subtracting one Array from another in Ruby

查看:60
本文介绍了在 Ruby 中从另一个数组中减去一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个任务数组 - 创建和分配.我想从创建的任务数组中删除所有分配的任务.这是我的工作,但凌乱的代码:

 @assigned_tasks = @user.assigned_tasks@created_tasks = @user.created_tasks#不显示分配给自己的已创建任务@created_not_doing_tasks = Array.new@created_tasks.each 做 |task|除非@assigned_tasks.include?(task)@created_not_doing_tasks <<任务结尾结尾

我相信有更好的方法.它是什么?谢谢:-)

解决方案

您可以在 Ruby 中减去数组:

[1,2,3,4,5] - [1,3,4] #=>[2,5]

<块引用>

ary - other_ary → new_ary 数组差异

返回一个新数组,它是原始数组的副本,删除任何也出现在 other_ary 中的项目.订单从原始数组.

它使用散列和 eql 比较元素?提高效率的方法.

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=>[ 3, 3, 5 ]

如果你需要类似 set 的行为,参见库类 Set.

请参阅 Array 文档.

I've got two arrays of Tasks - created and assigned. I want to remove all assigned tasks from the array of created tasks. Here's my working, but messy, code:

    @assigned_tasks = @user.assigned_tasks
    @created_tasks = @user.created_tasks

    #Do not show created tasks assigned to self
    @created_not_doing_tasks = Array.new
    @created_tasks.each do |task|
        unless @assigned_tasks.include?(task)
            @created_not_doing_tasks << task
        end
    end

I'm sure there's a better way. What is it? Thanks :-)

解决方案

You can subtract arrays in Ruby:

[1,2,3,4,5] - [1,3,4]  #=> [2,5]

ary - other_ary → new_ary Array Difference

Returns a new array that is a copy of the original array, removing any items that also appear in other_ary. The order is preserved from the original array.

It compares elements using their hash and eql? methods for efficiency.

[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] #=> [ 3, 3, 5 ]

If you need set-like behavior, see the library class Set.

See the Array documentation.

这篇关于在 Ruby 中从另一个数组中减去一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆