我有一系列哈希。每个条目如下所示:
- !map:Hashie::Mash
name: Connor H Peters
id: "506253404"
我正在尝试创建第二个数组,其中只包含id值。
["506253404"]
我正在这样做
second_array = first_array.map { |hash| hash[:id] }
但是我收到了这个错误
TypeError in PagesController#home
can't convert Symbol into Integer
如果我尝试
second_array = first_array.map { |hash| hash["id"] }
我得到了
TypeError in PagesController#home
can't convert String into Integer
我做错了什么?谢谢你的阅读。
答案 0 :(得分:6)
你正在使用Hashie,它与ruby core中的Hash不同。查看Hashie github repo,您似乎可以访问哈希键作为方法:
first_array.map { |hash| hash.id }
尝试一下,看看是否有效 - 确保它不会返回object_id。因此,您可能需要通过first_array.map { |hash| hash.name }
进行仔细检查,看看您是否真的在访问正确的数据。
然后,如果它是正确的,你可以使用proc来获取id(但更简洁一点):
first_array.map(&:id)
答案 1 :(得分:0)
这听起来像是在地图块中,哈希实际上并不是哈希 - 由于某种原因它是一个数组。
结果是[]方法实际上是一个数组访问器方法,需要一个整数。例如。 hash [0]有效,但不是hash [“id”]。
你可以尝试:
first_array.flatten.map{|hash| hash.id}
这将确保如果你有任何嵌套数组,那么嵌套就被删除了。
或者
first_array.map{|hash| hash.id if hash.respond_to?(:id)}
但无论哪种方式,你都可能会出现意想不到的行为。