如何从数组中获取单个项目?

时间:2021-05-29 04:16:04

I'm using MongoDB and Mongo Mapper and need to find an embedded document inside of an array. There has to be a simpler way to do this than the way I got working which is:

我正在使用MongoDB和Mongo Mapper,需要在数组中找到一个嵌入式文档。必须有一种比我工作方式更简单的方法,即:

@obj.subitems.each do |c|
  if (c.slug.eql? params[:id])
    @subitem = c # this is the variable i need
  end
end

Thanks

1 个解决方案

#1


3  

@subitem = @obj.subitems.detect { |c| c.slug.eql? params[:id] }

http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-detect

#1


3  

@subitem = @obj.subitems.detect { |c| c.slug.eql? params[:id] }

http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-detect