2015-09-08 202 views
1

我似乎無法將項目添加到散列。如何將散列元素添加到另一個散列?

我有以下方法,有一個散列傳入和意圖是傳出一個新的哈希從原來的。我已經證實,關鍵是一個字符串,其他兩個元素是浮動。當我請求時,b_name,lat和lng都會打印到日誌中。

def construct_paint_hash(list) 
    full_list = Hash.new 
    num = 100 
    list.each do |thing| 

     puts num 
     b_name = thing["name"] 
     puts b_name 
     lng = thing["longitude"] 
     lat = thing["latitude"] 
     full_list["#{b_name}"]=[lng, lat] 
     # full_list[:dsfsd] = "dsfdsfds" 
     num +=100 
    end 
    return full_list 
end 

以下是錯誤我得到:

Completed 500 Internal Server Error in 377ms (ActiveRecord: 0.0ms) 

TypeError (no implicit conversion of String into Integer): 
    app/controllers/welcome_controller.rb:42:in `[]' 
    app/controllers/welcome_controller.rb:42:in `block in construct_paint_hash' 
    app/controllers/welcome_controller.rb:39:in `each' 
    app/controllers/welcome_controller.rb:39:in `construct_paint_hash' 
    app/controllers/welcome_controller.rb:11:in `index' 

到底什麼我做錯了嗎?

+1

我可以看到代碼調用'construct_paint_hash(名單)'? –

+0

'LAT = get_lat()' 'LNG = get_lng()' 'thing_search = HTTParty.get(construct_location_search(緯度,經度))[ 「數據」]' 'thing_location_hash = construct_paint_hash(thing_search)' 'puts construct_paint_hash(thing_location_hash)' – notthehoff

+0

對評論災難感到抱歉 – notthehoff

回答

0

您的代碼似乎沒問題,但您可以使用以下代碼snippet。我假設你listparams如下

list = [{"name" => "dhaka", "longitude" => 23.44, "latitude" => 24.55}, {"name" => "usa", "longitude" => 23.44, "latitude" => 24.55}] 

然後重寫construct_paint_hash如下

def self.construct_paint_hash(list) 
    data = list.collect { |l| {l["name"] => [l["longitude"], l["latitude"]]} } 
    return data.inject(:merge) 
end 
相關問題