From: yermej Date: 2008-05-26T05:34:33+09:00 Subject: Re: A simple newbie question (arrays and strings) On May 25, 3:17 pm, koichirose wrote: > Today I started programming in ruby. > Here's what I managed to do so far: > > string = Dir.entries(".") > string.delete_at(0) > string.delete_at(0) > > 1. I get a list of files > 2-3. I delete the first two elements ('.' and '..') > > Now my files are all like "something - some other thing" > I want to split them: > > string.each do |s| > puts s.split("-")[0] > end > > So it outputs the "something" part in my filenames. > Now I'd like to remove duplicate entries (.uniq method right?). > Can it be done in a single line? If not, how do i get an array > containing only the "something" part to work on with .uniq? > > I tried with some loops, to create a new array with the splitted string > in it, but my PHP approach doesn't work: > i = 0 > for i in string > splitted[i] = i.split("-")[0] > i += 1 > end > > Thank you! One way would be to use Dir.glob: unique_array = Dir.glob('*-*').map {|f| f.split('-')[0]}.uniq Then you only get filenames that have - in them. Or: unique_array = Dir.entries('.')[2..-1].map {|f| f.split('-')[0]}.uniq But starting from here: > string = Dir.entries(".") > string.delete_at(0) > string.delete_at(0) string.map! {|f| f.split('-')[0]}.uniq!