Prabhu Chaitanya varma
Prabhu Chaitanya varma

Reputation: 118

Why "uniq/uniq!" method is not working on following array

The var_arry contains the all instance variables of the class. But I want the array without duplicates. How can I get please help me.

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!

I get following output. But I want to eliminate the duplicate values for this I use .uniq! method but it cant work

@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  

Upvotes: 0

Views: 421

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You put instances of MatchData in your array, produced by this line:

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

Don’t be confused by puts output, it calls to_s internally on printed entities, so you get stringified representation of your actual MatchData instances.

Array#uniq! compares values by it’s hash and eql? for efficiency. To put strings, use:

var[1] if var[1]

Or, even better:

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

The latter will map lines to either matched value or nil. compact will get rid of nils and uniq will do what you expected.

Upvotes: 3

Related Questions