我有一个处理目录中前N个文件的函数:
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
我只是想知道是否有更多的ruby-way方法来编写这个函数?
答案 0 :(得分:4)
Slice数组[]
并使用inject
收集Tweet
中的所有TweetCollection
个对象。使用File.read
在一次方法调用中返回给定path
处文件的内容。
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
我还用实例变量替换了你的全局变量;我不知道你的方法的上下文,所以这可能是不可能的。
答案 1 :(得分:1)
Dir["cache/*"][0...cnt] do |path|
...
end
答案 2 :(得分:0)
另一种方式:
Dir["cache/*"].take(cnt)