Create array and append key and value in each

I want to create a array and then to insert values for each key (key should be the value from each). But seems to not working. This is my code.

@options = %w(Services Resources)
@images  = []
@options.each do |value|
    @images[value] << Media::Image.where(type: "Media::#{value.singularize}Image")
end

Upvotes: 0

Views: 101

Answers (2)

Kevin.Xin
Kevin.Xin

Reputation: 86

@images is a Array, Array can not use as a Hash. Maybe you want create a Hash like this

@images = Hash.new {|h,k| h[k]=[]}

Upvotes: 0

Brozorec
Brozorec

Reputation: 1183

@images is an array so referencing an element in it should be @images[Integer] and value is a string (in the first iteration it's "Services" and in the second "Resources"). Instead, what would work for you is Hash:

@options = %w(Services Resources)
@images  = {}
@options.each do |value|
    @images[value] = Media::Image.where(type: "Media::#    {value.singularize}Image")
end

Upvotes: 2

Related Questions