0

I have a problem with adding a new key and value to a hash in ruby on rails. The method looks like this with two debug prints and should simply add the provider key with index + 1 as value, in order to access the provider with the right ID later.

search_result.each_with_index do |articles, index|
  puts "merge-articles: #{articles}"
  articles.each{ |article| article[:provider] = index + 1;}
  puts "merge-articles(later): #{articles}"
end                                        

I get those output from the puts, which look quite good to my mind:

merge-articles: [{:ean=>"9780234474278", :author=>"Dan Brown", :name=>"The Da Vinci Code", :price=>19.65, :image=>"www.google.de/image.png"}]
merge-articles(later): [{:ean=>"9780234474278", :author=>"Dan Brown", :name=>"The Da Vinci Code", :price=>19.65, :image=>"www.google.de/image.png", :provider=>2}]

The Spec which only tests if the keys exist gets this error:

 Failure/Error: HomeController.merge(@no_same_items_merge).each do |item|
 TypeError:
   can't convert Symbol into Integer
 # ./app/controllers/home_controller.rb:41:in `[]='
 # ./app/controllers/home_controller.rb:41:in `block (2 levels) in merge'
 # ./app/controllers/home_controller.rb:41:in `each'
 # ./app/controllers/home_controller.rb:41:in `block in merge'
 # ./app/controllers/home_controller.rb:39:in `each'
 # ./app/controllers/home_controller.rb:39:in `each_with_index'
 # ./app/controllers/home_controller.rb:39:in `merge'
 # ./spec/controllers/home_controller_spec.rb:104:in `block (5 levels) in <top (required)>'

Edit: The RSpec test looks like this:

    it "should return an array of right formatted hashes" do
      HomeController.merge(@no_same_items_merge).each do |item|
        item.should have_key(:name)
        item.should have_key(:ean)
        item.should have_key(:author)
        item.should have_key(:description)
        item.should have_key(:url)
        item.should have_key(:prices)
        item.should have_key(:images)
      end
    end   

Thanks for your help!

4
  • Can you paste in the rspec test? Could be a problem there and not in the code. Commented Mar 14, 2013 at 12:49
  • 4
    That error strongly implies that in the spec, article is an Array, not a Hash; check how you're defining article in the spec. Commented Mar 14, 2013 at 12:51
  • @bloopletech is right, article is an Array of Hash. Commented Mar 14, 2013 at 12:53
  • Ah, I found my mistake, I was testing with the wrong parameter for the test Commented Mar 14, 2013 at 13:06

1 Answer 1

2

In the spec, set article to be an Array, not a Hash.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.