【问题标题】:How do I add hash elements to another hash?如何将哈希元素添加到另一个哈希?
【发布时间】:2015-12-03 13:04:27
【问题描述】:

我似乎无法将项目添加到哈希中。

我有以下方法,其中传入了一个散列,目的是传递一个由原始散列制成的新散列。我已经验证了键是一个字符串,而其他两个元素是浮点数。当我请求时,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'

我到底做错了什么?

【问题讨论】:

  • 我可以看到调用construct_paint_hash(list)的代码吗?
  • lat = get_lat()lng = get_lng()thing_search = HTTParty.get(construct_location_search(lat,lng))["data"]thing_location_hash = construct_paint_hash(thing_search)puts construct_paint_hash(thing_location_hash)
  • 对评论灾难感到抱歉
  • 你搞定了。你说我多次调用它。我想“这家伙疯了!”当我看到我一直盯着一个小时的代码时......我删除了真正只是为了测试而放入的 puts 语句,它可以工作。把它放在下面的答案中,如果你愿意,我会检查它是否已解决
  • 我觉得它看起来不错 :) 耶!

标签: ruby-on-rails ruby hash


【解决方案1】:

您的代码看起来不错,但您可以使用以下代码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

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 1970-01-01
    • 2019-05-31
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2020-12-08
    • 2013-01-10
    相关资源
    最近更新 更多