From: "Sebastjan H." Date: 2012-05-02T21:15:25+09:00 Subject: Re: array of strings - finding letter combinations Hi Jan, thank you so much for this. I went through the code and I think I understand most of it. I am only having hard time understanding the beginning: > str = 'abc&exyz' > str[/(?<=&)[a-z]/] What do these two lines define. I guess the second one is the regex, what about the first one. And moreover, how are these two related? I apologise if my questions are puzzling... I plan to have the file with strings uploaded and then execute this code and probably print the results in a file as well. regards, seba Jan E. wrote in post #1059205: > Hi, > > Sebastjan H. wrote in post #1059172: >> >> I am new to ruby and I want to learn by examples and here is one from my >> everyday work. I have an array of strings where each string contains a >> combination of an ampersand and a letter (&e). The trick is, this >> combination may only appear once in the whole array, so none of the >> other strings may contain the same combination. > > You could start off by selecting the letter after "&" in a string. This > can be done with a regex: > > str = 'abc&exyz' > str[/(?<=&)[a-z]/] > > Then you iterate over the array, collecting the duplicate strings and > the used characters: > > strings = ['&a', '&b', '&c', '&a'] > used_chars = [] > duplicates = [] > strings.each_with_index do |str, i| > char = str[/(?<=&)[a-z]/] > duplicates << i if used_chars.include? char > used_chars << char > end > > And after this you iterate over the duplicate strings and suggest and > unused character (or raise in error, if there are none left): > > duplicates.each do |index| > unused = ('a'..'z').find {|char| not used_chars.include? char} > if unused.nil? > raise 'all letters taken' > else > puts "combination #{strings[index][/&[a-z]/]} already taken.", > "Use &#{unused} instead?" > used_chars << unused > end > end > > The actual processing of the user input has to be added, of course. -- Posted via http://www.ruby-forum.com/.