简体   繁体   中英

Get value of a key in an array of hashes

I'm fairly new to ruby on rails and I'm having some trouble trying to extract a key value from an array of hashes (@sorted) when using options_from_collection_for_select in my html.haml file.

So far I've tried

options_from_collection_for_select(@sorted, "#{@sorted['id']}", 
"#{@sorted['name']}")

options_from_collection_for_select(@sorted, @sorted['id'], @sorted['name'])

But both give me a "Can't convert string to integer" error I've tried calling to_i but the error still persists.

Array of Hashes (@sorted)

@sorted => [{"id"=>"51a7ba4154b3289da800000f", "name"=>"Book1", "count"=>8},
{"id"=>"519d24ed54b328e512000001", "name"=>"Book2", "count"=>5},
{"id"=>"5258917b54b32812cd000003", "name"=>"Book3", "count"=>1}]

使用options_for_select

options_for_select(@sorted.map{|hash| [hash["id"],hash["name"]]})

Remember that when you have an array, it is made up of multiple elements, and the methods you call on it are array methods, not methods for the elements inside.

In this case, each element is a hash, so your array looks like the following:

[ {"id" => 1, "name" => "Name 1"}, {"id" => 2, "name" => "Name 2" ]

The class itself is an array. You can index in to an array like so:

myArray[1]

This method takes an integer and finds the n th element. So doing:

@sorted[1]

Would return this hash element:

{"id" => 2, "name" => "Name 2"}

And now you can call hash methods on it. This is why you were getting that error, because the Array#[] method assumed you were giving it an integer to index in to the array, but you were giving it a string - a string that could not be converted in to an integer.

So in your particular case, you probably mean to do:

@sorted.first["id"], @sorted.first["name"]

(Doing @sorted.first is an alternative to @sorted[0] to get the first element in an array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM