开发者

Get an asset's numerical position in an array in Ruby on Rails

开发者 https://www.devze.com 2023-01-06 00:12 出处:网络
I\'m working with a list of assets, sorted alphabetically (through another method). I would like to assign a value to the \"position\" key, which essentially just says where this particular asset appe

I'm working with a list of assets, sorted alphabetically (through another method). I would like to assign a value to the "position" key, which essentially just says where this particular asset appears in the ordered list of all assets. Here is the code I'm working with now (:position left 开发者_如何学JAVAblank on purpose):

@active_resources.each do |asset|
  @asset_data[asset.id] = {
    :name => asset.name,
    :services => asset.active_services.collect{|service| 
      {:duration => service.duration, :name => service.name, :id => service.id}
    },
    :position => 
  }
end

Thank you in advance.


If the list is already sorted (as you mention) and is implemented as an Array, you can use the Array::index method to determine the numerical index of an item in the array.

If you are trying assign position values for the entire array, you could use something like:

@active_resources.each_with_index {|asset,idx|
    @asset_data[asset.id][:position] = idx
}
0

精彩评论

暂无评论...
验证码 换一张
取 消