tags:

views:

37

answers:

3

I have a function which prosecces first N files in the direcory:

def restore(cnt)
  $LOG.debug "store_engine : restore tweets from cache (cnt = #{cnt})"

  result = TweetCollection.new

  Dir["cache/*"].each do |path|
    cnt = cnt - 1
    File.open(path) do |f|
      result.append(Tweet.construct(:friends, :yaml, f.read))
    end
    if cnt == 0
      return result
    end      
  end

  result
end

I'm just wondering if there is a more ruby-way method to write this function?

+1  A: 

Slice it:

Dir["cache/*"][0...cnt] do |path|
  ...
end
jleedev
Wonderfull. Thanks.
demas
+4  A: 

Slice the array with [] and use inject to collect all Tweet objects in the TweetCollection. Use File.read to return the contents of the file at the given path in one method call.

def restore(count)
  @log.debug "store_engine: restore tweets from cache (cnt = #{count})"
  Dir["cache/*"][0...count].inject(TweetCollection.new) do |tweets, path|
    tweets.append Tweet.construct(:friends, :yaml, File.read(path))
    tweets
  end
end

I have also replaced your global variable by an instance variable; I don't know the context of your method, so this may not be possible.

molf
+1. Something about inject that my brain tries to block it out.. nicely applied here.
Gishu
A: 

Another way:

Dir["cache/*"].take(cnt)
glenn jackman