首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么"uniq/uniq!“方法不处理以下数组

为什么"uniq/uniq!“方法不处理以下数组
EN

Stack Overflow用户
提问于 2015-04-30 09:11:37
回答 1查看 389关注 0票数 0

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

代码语言:javascript
复制
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!方法,但是它不能工作

代码语言:javascript
复制
@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  
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-30 09:25:55

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

代码语言:javascript
复制
var = line.match /@(\w+_\w+|\w+)/

不要被puts输出搞糊涂,它在打印实体上内部调用to_s,这样就可以得到实际MatchData实例的字符串表示。

Array#uniq!通过它的hasheql?来比较值的效率。若要放置字符串,请使用:

代码语言:javascript
复制
var[1] if var[1]

或者更好的是:

代码语言:javascript
复制
lines = file.map do |line|
  $1 if line =~ /@(\w+_\w+|\w+)/
end.compact.uniq

后者将将线条映射到匹配值或零。compact会摆脱nils,uniq会做你想做的事情。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29963621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档