I have a Ruby hash which is passed to a hidden field. How do I extract this hash into JavaScript arrays that I can work with? I need to access the key/value pairs in JavaScript.
Ruby Hashes. In Ruby, a hash is a collection of key/value pairs that stores information. Hash values can be accessed by calling on the key that corresponds to each value. These values can be strings, integers, arrays, or even other hashes. Values can be reassigned with the equal sign.
A Hash maps each of its unique keys to a specific value. A Hash has certain similarities to an Array, but: An Array index is always an Integer. A Hash key can be (almost) any object.
In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.
Ruby code:
state = { 'Waiting' => { name: 'Waiting now', color: 'btn-default' },
'Trying' => { name: 'Trying now', color: 'btn-danger' },
'Answered' => { name: 'Answered now', color: 'btn-success' } }
javascript code:
var state = JSON.parse('#{raw(state.to_json)}');
Use my_awesome_ruby_hash.to_json
and then you can simply either eval
it in js or use parseJSON
. You might need to require 'json'
(not in Rails).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With