From: tjnogueira@... Date: 2008-12-26T20:21:48+09:00 Subject: Re: Buiding anamgrams That's it. In ruby 1.8.6 you cant use this form , only for 1.8.7 and prior ... I tested here and the code works perfectly. About your class: class Anagrams >> attr :word >> include Enumerable >> include Comparable >> >> def <=>(other) >> self.word <=> other.word >> end >> >> def each(&block) >> @word.chars >> end >> >> def initialize(word) >> @word = word >> end >> >> end i really dont understant what it means. Explain better. King regards tiago On Fri, 26 Dec 2008 19:50:00 +0900, Robert Klemme wrote: > On 26.12.2008 10:30, andrea wrote: >> I'm studying ruby (and I really love it even more than python) and I >> want to do a little exercise. > > Welcome to the pack! What a nice Christmas occupation. :-) > >> I want to create an efficient module to generate every possible >> anagrams of a word, of any given size... > > Do you really mean "anagrams" or rather "permutations"? To decide on > anagrams you likely need some kind of dictionary which is significantly > more difficult than just permuting. > >> I already done this in python, I want to see how can it be elegant in >> ruby... >> I need a good permutation algorithm (this >> > http://www.cut-the-knot.org/Curriculum/Combinatorics/JohnsonTrotter.shtml >> works fine) and I'd like to use enumerators in the best and most >> efficient way. > > From 1.8.7 on you can do this > > irb(main):009:0> "abc".scan(/./).permutation {|x| p x.join} > "abc" > "acb" > "bac" > "bca" > "cab" > "cba" > => ["a", "b", "c"] > irb(main):010:0> "abc".chars.to_a.permutation {|x| p x.join} > "abc" > "acb" > "bac" > "bca" > "cab" > "cba" > => ["a", "b", "c"] > irb(main):011:0> > > Now you only need a filter that properly decides which of those is a > proper word and use that to decide which words to print and which not. > >> I also looked at callcc which is great for backtracking, could be used >> in this case?? > > I would try to avoid it as it makes code very hard to read - at least > for me. :-) > >> thanks for any help >> >> A basic structure like that could be fine? >> class Anagrams >> attr :word >> include Enumerable >> include Comparable >> >> def <=>(other) >> self.word <=> other.word >> end >> >> def each(&block) >> @word.chars >> end >> >> def initialize(word) >> @word = word >> end >> >> end > > What exactly should be the responsibility of this class? Especially, > why do you call it "anagrams" but store only one word in it? > > Cheers > > robert > > -- > remember.guy do |as, often| as.you_can - without end