From: Panagiotis Atmatzidis Date: 2012-07-09T05:59:03+09:00 Subject: Re: Troubled while trying to create list from hash Hello, On 8 Ιουλ 2012, at 18:16 , Brian Candler wrote: > Panagiotis Atmatzidis wrote in post #1067854: >> I'm not even sure if the enumerable method 'any' is used >> correctly. > > No, it's not how it's intended to be used. > > The idea behind 'any?' is to return true if the block returns true for > any of the elements. So the block is expected to return a "truthy" > value. > > puts [1,3,7,4].any? { |x| x > 10 } # false > puts [1,3,7,4].any? { |x| x > 5 } # true > > However, because your block ends with a "p" statement, which always > returns nil, this will be treated as false always. > > So in this case, 'any?' is really behaving just as 'each', just > iterating over every single element. Also, you're ignoring the return > value from 'any?' Thanks for the detailed explanation. I need to get much more accustomed to the enumerable and other elementary ruby methods apparently :-/ >> Any hints or ideas on how to adjust/improve this piece of code are >> welcomed! > > Why are you not just taking 'sorted.first' as the most frequently found > element? > > If you are concerned about getting all the equal top values, then I'd do > something like this: > > best_count = sorted[0][1] > return sorted.select { |data,no| no == best_count } The reason is that I didn't thought about it! All solutions that came to mind involved several lines of code and functions which made the entire process feel utterly complicated and wrong for such an easy task. I was sure that there was an easy - 1 or 2 lines of code - to do this. Your solution works like a charm! Thanks for the code snippet! > Regards, > > Brian. > > -- > Posted via http://www.ruby-forum.com/. > regards, Panagiotis Atmatzidis ----------------------------- Pharmacy Student at VFU email4lists: ml@convalesco.org More info: http://about.me/atmosx The wise man said: "Never argue with an idiot, he brings you down to his level and beat you with experience."