Ruby - "can't convert Symbol into Integer" when try to access data in array

13,134

Your @array is actually a hash. It is formated like following:

{ 
  'name1' => [{:upc => "..."},{:upc => "..."}],
  'name2' => [{:upc => "..."},{:upc => "..."}],
  #...
}

Since it is a Hash, you can use 2 arguments in the each (works for map also) method (one for the key, the other for the value):

@array.each do |name, array|
  product = Product.new
  product.sku = name # returns "C1"
  array.each do |data|
    data[:upc]
    data[:name]
    #etc...
  end
end
Share:
13,134

Related videos on Youtube

user984621
Author by

user984621

Updated on July 03, 2022

Comments

  • user984621
    user984621 almost 2 years

    Here's a sample of array:

    {"C1"=>[
            {:upc=>"51857195821952", :product_id=>"1234", :name=>"name", :price=>" $15 ", :color=>"green", :size=>"L", :description=>"descr"},
            {:upc=>"352353wegs", :product_id=>"456", :name=>"name2", :price=>"$21", :color=>"black", :size=>"S", :description=>"descr"}, # ...
           ],
     #...
    }
    

    And here as I am trying to fetch data from that array:

    @array.each do |p|
      product = Product.new
      product.sku = p[0]
      product.name = p[1][0][:name] #can't convert Symbol into Integer
      price = p[1].select{ |pr| !pr[:price].nil? and pr[:price] != "0" }.min_by{ |i| i[:price].to_f }[:price]
      product.price = "%.2f" % (price.to_f)
      ...
    end
    

    Every time I try to fetch data from the array, I get on the line product.name = the error can't convert Symbol into Integer.

    What is wrong in this case? I spent a part of afternoon on this issue, but unfortunately I still cannot figure out it...

    Thanky you

  • user984621
    user984621 about 11 years
    thank you. But how can I access the price element? The current way how I am trying to obtain that generate error private method 'select' called for "\"":String
  • MrYoshiji
    MrYoshiji about 11 years
    You can access to it using data[:price] but this will return a string like " 15$ ", you have to strip it and gsub the '$' before converting it into a Float