Ruby 处理目录中的前n个文件
我有一个函数,用于处理目录中的前N个文件:Ruby 处理目录中的前n个文件,ruby,Ruby,我有一个函数,用于处理目录中的前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.cons
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的方法来编写此函数?:
包含[]
的数组,用于收集TweetCollection
中的所有Tweet
对象。用于在一次方法调用中返回给定路径下的文件内容
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
我还用实例变量替换了全局变量;我不知道您的方法的上下文,因此这可能不可能。另一种方法:
Dir["cache/*"].take(cnt)
+1.关于注射的东西,我的大脑试图阻止它。。这里用得很好。
Dir["cache/*"].take(cnt)