From: Christopher Dicely Date: 2009-02-11T11:02:16+09:00 Subject: Re: a better way to do this job? On Tue, Feb 10, 2009 at 1:11 AM, Zhenning Guan wrote: > topics.each do |f| > times +=1 > puts f.title > if times > 4 > break > > > a little ugly, doesn't it? Assuming there is a times=0 before this, and what you want to do is print each topic title if there are 5 or less topics, but only those 5 if there are more, then: topics[0..4].each {|f| puts f.title} or: topics.each_with_index do |f, i| puts f.title break if i > 4 end is probably the best way to do it (the first is, IMO, cleaner and more understandable, the latter seems like it would somewhat more efficient because it doesn't create an auxiliary array, though for this size it doesn't matter, it conceivably might for very large arrays.) 5.times {|i| puts topics[i].title} works if there are 5 or more topics, but will dump nils at the end if there are less than 5.