[英]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.