开发者

Why am I getting this TypeError - "can't convert Symbol into Integer"?

I have an array of hashes. Each entry looks like this:

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

I'm trying to create a second array, which contains just the id values.

["506253404"]

This is how I'm doing it

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

But I'm getting 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.


You're using Hashie, which isn't the same as Hash from ruby core. Looking at the Hashie github repo, it seems that you can access hash keys as methods:

first_array.map { |hash| hash.id }

Try this out and see if that works--make sure that it doesn't return the object_id. As such, you may want to double-check by doing first_array.map { |hash| hash.name } to see if you're really accessing the right data.

Then, provided it's correct, you can use a proc to get the id (but with a bit more brevity):

first_array.map(&:id)


This sounds like inside the map block that hash is not actually a hashie - it's an array for some reason.

The result is that the [] method is actually an array accessor method and requires an integer. Eg. hash[0] would be valid, but not hash["id"].

You could try:

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

which would ensure that if you do have any nested arrays that nesting is removed.

Or perhaps

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

But either way you may end up with unexpected behaviour.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜