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 发布于 2015-04-30 09:25:55
将MatchData的实例放入数组中,由以下行生成:
var = line.match /@(\w+_\w+|\w+)/不要被puts输出搞糊涂,它在打印实体上内部调用to_s,这样就可以得到实际MatchData实例的字符串表示。
Array#uniq!通过它的hash和eql?来比较值的效率。若要放置字符串,请使用:
var[1] if var[1]或者更好的是:
lines = file.map do |line|
$1 if line =~ /@(\w+_\w+|\w+)/
end.compact.uniq后者将将线条映射到匹配值或零。compact会摆脱nils,uniq会做你想做的事情。
https://stackoverflow.com/questions/29963621
复制相似问题