2015-09-08 157 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 
相关问题