簡體   English   中英

如何將哈希元素添加到另一個哈希?

[英]How do I add hash elements to another hash?

我似乎無法將項目添加到哈希中。

我有以下方法,其中傳入了哈希值,目的是傳出由原始哈希值構成的新哈希值。 我已經驗證了鍵是一個字符串,另外兩個元素是浮點數。 當我請求時,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'

我到底在做什么錯呢?

您的代碼似乎還可以,但是您可以使用以下代碼snippet 我假設您的list params如下

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

暫無
暫無

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

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