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
}
精彩评论