[英]How do I add hash elements to another hash?
I do not seem to be able to add items to a hash. 我似乎无法将项目添加到哈希中。
I have the following method that has a hash passed in and the intent is to pass out a new hash made from the original. 我有以下方法,其中传入了哈希值,目的是传出由原始哈希值构成的新哈希值。 I have verified that the key is a string and the other two elements are floats. 我已经验证了键是一个字符串,另外两个元素是浮点数。 b_name, lat and lng all print to the logs when I request. 当我请求时,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
Here is the error I am getting: 这是我得到的错误:
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'
What the heck am I doing wrong here? 我到底在做什么错呢?
Your code seems okay, but you can use the following code snippet
. 您的代码似乎还可以,但是您可以使用以下代码snippet
。 I assume your list
params
as following 我假设您的list
params
如下
list = [{"name" => "dhaka", "longitude" => 23.44, "latitude" => 24.55}, {"name" => "usa", "longitude" => 23.44, "latitude" => 24.55}]
Then rewrite your construct_paint_hash
as following 然后如下重写你的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.