簡體   English   中英

在rails上的ruby中添加哈希值

[英]Adding value to hash in ruby on rails

我有一個問題,在rails上的ruby中添加一個新的鍵和值。 該方法看起來像這樣,有兩個調試打印,只需添加索引+ 1作為值的提供程序密鑰,以便稍后訪問具有正確ID的提供程序。

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                                        

我得到了看跌期權的輸出,這看起來非常好我的想法:

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}]

僅測試密鑰是否存在的規范會收到此錯誤:

 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)>'

編輯:RSpec測試如下所示:

    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   

謝謝你的幫助!

在規范中,將article設置為Array ,而不是Hash

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM