ruby on rails - Generation of table and accessing elements of a Array of Hashes -
i have following array of hashes in rails application:
a = ["{\"row1\"=>{\"correct\"=>{\"h\"=>\"10\", \"m\"=>\"11\", \"l\"=> \"12\"}, \"wrong\"=>{\"h\"=>\"2\", \"m\"=>\"2\", \"l\"=>\"4\"}, \"blank \"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"3\"}}, \"row2\"=>{\"correct \"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"4\"}, \"wrong\"=>{\"h \"=>\"4\", \"m\"=>\"6\", \"l\"=>\"6\"}, \"blank\"=>{\"h\"=>\"7\", \"m\"=>\"5\", \"l\"=>\"6\"}}, \"row3\"=>{\"correct\"=>{\"h\"=>\"4\", \"m\"=>\"6\", \"l\"=>\"7\"}, \"wrong\"=>{\"h\"=>\"6\", \"m\"=>\"7\", \"l\"=>\"5\"}, \"blank\"=>{\"h\"=>\"7\", \"m\"=>\"9\", \"l\"=> \"3\"}}}"]
i want access elements , create database table it, in following format
row1 correct h=10, m=11,l=12 wrong h=2, m=2,l=4 blank h=2, m=4,l=3
...and similar row2 , row3.
how can that?
i tried access value using
a["row1"]["correct"]["h"]
...but returns nil value.
how access values of array of hashes?
you need first convert string hash can done follows:
require 'json' = ["{\"row1\"=>{\"correct\"=>{\"h\"=>\"10\", \"m\"=>\"11\", \"l\"=> \"12\"}, \"wrong\"=>{\"h\"=>\"2\", \"m\"=>\"2\", \"l\"=>\"4\"}, \"blank \"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"3\"}}, \"row2\"=>{\"correct \"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"4\"}, \"wrong\"=>{\"h \"=>\"4\", \"m\"=>\"6\", \"l\"=>\"6\"}, \"blank\"=>{\"h\"=>\"7\", \"m\"=>\"5\", \"l\"=>\"6\"}}, \"row3\"=>{\"correct\"=>{\"h\"=>\"4\", \"m\"=>\"6\", \"l\"=>\"7\"}, \"wrong\"=>{\"h\"=>\"6\", \"m\"=>\"7\", \"l\"=>\"5\"}, \"blank\"=>{\"h\"=>\"7\", \"m\"=>\"9\", \"l\"=> \"3\"}}}" ] hash_string = a[0] hash = json.parse hash_string.gsub("\n", '').gsub('=>', ':') # access hash now: hash["row1"]["correct"]["h"] # => 10
btw, please note there typo. instead of correct
, key correct
small c
instead of capital c
.
hope helps : )
Comments
Post a Comment