Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby hash to JavaScript

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.

like image 369
newbie_86 Avatar asked Mar 24 '11 12:03

newbie_86


People also ask

What is a ruby Hash 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.

Is Ruby Hash an object?

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.

What is a Hash in Ruby?

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.


2 Answers

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)}');
like image 163
Lane Avatar answered Sep 24 '22 05:09

Lane


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).

like image 26
Jakub Hampl Avatar answered Sep 24 '22 05:09

Jakub Hampl