Why do I get this TypeError - "cannot convert character to integer"?

I have an array of hashes. Each entry is as follows:

- !map:Hashie::Mash 
  name: Connor H Peters
  id: "506253404"

I am trying to create a second array containing only id values.

["506253404"]

This is how i do it

second_array = first_array.map { |hash| hash[:id] }

But I get this error

TypeError in PagesController#home
can't convert Symbol into Integer

If i try

second_array = first_array.map { |hash| hash["id"] }

I get

TypeError in PagesController#home
can't convert String into Integer

What am I doing wrong? Thanks for reading.

+3
source share
2 answers

You are using Hashie, which is not like Hash from the ruby ​​core. Looking at the Hashie github repo, it seems like you can refer to hash keys as methods:

first_array.map { |hash| hash.id }

, - , object_id. , , first_array.map { |hash| hash.name }, , .

, , proc ( ):

first_array.map(&:id)
+6

, - - .

[] . . hash [0] , hash [ "id" ].

:

first_array.flatten.map{|hash| hash.id}

, - , .

, ,

first_array.map{|hash| hash.id if hash.respond_to?(:id)}

.

0

Source: https://habr.com/ru/post/1781350/


All Articles