0

这是我所拥有的:

def existing_photos
  @existing_photos = Array.new
  event.photos.each do |ep|
    @existing_photos << URI.unescape(ep.dropbox_path.split('/').last) rescue []
  end
  @existing_photos
end

它从数据库查询中返回一个文件名数组。我敢肯定有一种更像红宝石的方式来做到这一点。

我也有一个类似的方法,它对 dropbox-apils结果做同样的事情。

def all_photos
  @all_photos = Array.new
  @dropbox_files.each do |dbf|
    @all_photos << dbf.path.split('/').last
  end
  @all_photos
end

我认为也应该优化。提前致谢!

4

1 回答 1

3

我可能会这样做...

def existing_photos
  event.photos.map { |ep|
    URI.unescape(ep.dropbox_path.sub(%r{.*/}, '') rescue nil
  }.compact
end

获取event.photos类似于数组的内容并使用块将其映射以将其转换为您想要的内容。最后压缩它以处理 nil 情况。的使用sub只是一种偏好,可能比分割路径和选择最后一个元素更快(但您可能需要计时查看)。

于 2012-11-27T23:00:44.277 回答