如何从Ruby中的结构数组中获取唯一的struct值?

时间:2021-04-09 12:41:52

I am fairly new to Ruby and was wondering if there is a way to extract unique struct values within an array.

我对Ruby很新,并且想知道是否有一种方法可以在数组中提取唯一的struct值。

I have the following struct:

我有以下结构:

Struct.new(:source_ip_address, :destination_ip_address, :port)

Within my code I am getting these struct values from a file, then storing them in an array:

在我的代码中,我从文件中获取这些结构值,然后将它们存储在数组中:

ip_port_list

So basically for each line in the file, a new struct is created. That struct is then added to the ip_port_list array. The next thing I am trying to do is pull out all the unique port values within the entire array. Is there a way to do this? Any help would be greatly appreciated.

所以基本上对于文件中的每一行,都会创建一个新的结构。然后将该结构添加到ip_port_list数组中。我要做的下一件事是拉出整个数组中的所有唯一端口值。有没有办法做到这一点?任何帮助将不胜感激。

1 个解决方案

#1


3  

ip_port_list.map(&:port).uniq

Should do it.

应该这样做。

#1


3  

ip_port_list.map(&:port).uniq

Should do it.

应该这样做。