这就是我所拥有的:
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它从数据库查询中返回一个文件名数组。我相信有一种更像ruby的方式可以做到这一点。
我也有一个类似的方法,对dropbox-api ls结果做同样的事情。
def all_photos
@all_photos = Array.new
@dropbox_files.each do |dbf|
@all_photos << dbf.path.split('/').last
end
@all_photos
end我认为这也应该被优化。提前感谢!
发布于 2012-11-28 07:00:44
我可能会这么做。
def existing_photos
event.photos.map { |ep|
URI.unescape(ep.dropbox_path.sub(%r{.*/}, '') rescue nil
}.compact
end获取类似于数组的event.photos,并使用块将其映射为您想要的内容。将其压缩在末尾,以处理nil情况。使用sub只是一种偏好,可能比拆分路径并选择最后一个元素更快(但您可能希望对其进行计时以查看)。
https://stackoverflow.com/questions/13594529
复制相似问题