From: Lars Haugseth Date: 2012-07-17T19:52:41+09:00 Subject: Re: What does this code do? On 07/16/2012 10:24 PM, Ryan Davis wrote: > > On Jul 15, 2012, at 19:19 , Mike Glaz wrote: > >> I'm reading through a tutorial and found a solution for it (because I'm >> stuck), but I don't understand some code, so I was hoping someone could >> shed some light on it: >> >> USERNAME_REGEX = /@\w+/i >> >> class Micropost < ActiveRecord::Base >> def people_replied >> users = [] >> self.content.clone.gsub!( USERNAME_REGEX ).each do |username| >> user = User.find_by_username(username[1..-1]) >> users << user if user >> end >> users >> end >> end > > This code is _so_ bad that I'd stop reading this tutorial and go read > some other tutorial. It'd bad enough that it shouldn't be explained as > it currently stands, honestly. Seconded. > Instead, I can show you how it (probably) should have been written: > > class Micropost < ActiveRecord::Base > def people_replied > content.scan(/@\w+/).map { |name| User.find_by_username name[1..-1] }.compact > end > end How about: def people_replied User.where :username => content.scan(/@(\w+)/) end -- Lars Haugseth