为什么"uniq/uniq!"方法不适用于以下数组



var_arry包含类的所有实例变量。但是我想要没有重复项的数组。我怎么能得到请帮助我。

file = open("sample.txt")    
var_arr = []
file.each do |line|
 var = line.match /@(w+_w+|w+)/
  if var != nil
   var_arr << var
  end
end
puts var_arr.uniq!

我得到以下输出。但是我想消除我使用.uniq!方法的重复值,但它不起作用

@event
@event
@event
@event
@event_participants
@event_participants
@event_participants
@event_participants
@event_participants
@event_participants
@event_participants
@event_participants
@project
@event
@project
@events
@projects
@events
@subscription
@admin
@subscription
@owners
@projects
@projects
@projects
@project_files
@project_file
@project_file
@project_file
@project_file
@sort_option
@sort_direction
@sort_filter
@sort_filter
@sort_filter
@sort_filter
@sort_filter
@sort_filter
@sort_filter
@sort_option
@sort_option
@sort_option
@sort_option
@sort_option
@sort_direction
@sort_direction
@sort_direction
@sort_direction
@sort_direction
@sort_filter
@projects
@projects
@sort_direction
@projects
@projects
@sort_option
@sort_filter
@projects
@projects
@message_template
@message_template
@message_template
@message_template
@message_template
@message_template
@message_template
@drag_evnt
@drag_evnt  

您将MatchData的实例放在数组中,由以下行生成:

var = line.match /@(w+_w+|w+)/

不要被puts输出所迷惑,它在打印实体上内部调用to_s,因此您可以获得实际MatchData实例的字符串化表示。

Array#uniq!通过其

hasheql?来比较值以提高效率。要放置字符串,请使用:

var[1] if var[1]

或者,甚至更好:

lines = file.map do |line|
  $1 if line =~ /@(w+_w+|w+)/
end.compact.uniq

后者会将行映射到匹配值或 nil。 compact将摆脱尼尔斯,uniq将按照您的期望行事。

相关内容

最新更新