如果元素不存在,则将其添加到数组中 [英] Add element to an array if it's not there already

查看:42
本文介绍了如果元素不存在,则将其添加到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Ruby 课程

I have a Ruby class

class MyClass
  attr_writer :item1, :item2
end

my_array = get_array_of_my_class() #my_array is an array of MyClass
unique_array_of_item1 = []

我想将 MyClass#item1 推送到 unique_array_of_item1,但前提是 unique_array_of_item1 不包含那个 item1> 还.我知道有一个简单的解决方案:只需遍历 my_array 并检查 unique_array_of_item1 是否已经包含当前的 item1.

I want to push MyClass#item1 to unique_array_of_item1, but only if unique_array_of_item1 doesn't contain that item1 yet. There is a simple solution I know: just iterate through my_array and check if unique_array_of_item1 already contains the current item1 or not.

有没有更有效的解决方案?

Is there any more efficient solution?

推荐答案

您可以使用 Set 而不是 Array.

You can use Set instead of Array.

这篇关于如果元素不存在,则将其添加到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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