1

I am trying to use the jQuery plugin jQCloud to create word clouds in a rails application.

The word cloud data needs to be in a format:

var word_array = [
  {text: "Lorem", weight: 15},
  {text: "Ipsum", weight: 9},
];

I currently have a ruby hash of word frequencies like:

{"people"=>111, "other"=>110}

How can I convert this into the required named javascript array, like:

[{text: "people", weight: 11},{text: "other", weight: 11}]

Any ideas or suggestions would be greatly appreciated!

Thanks

3 Answers 3

2

Just use map:

hash.map { |k, v| { text: k, weight: v } }
=> [{:text=>"people", :weight=>111}, {:text=>"other", :weight=>110}]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your help. In case anybody had the same issue I would like to add I also had to convert the result to json, which I did using the hash.to_json method. The resulting data in this format: [{"text":"people","weight":10},{"text":"other","weight":8}] worked if assigned manually like var words = [{"text":"pe.... but not if simply var words = <%= @data %>; To get the assigned data to be understood i had to had raw, like words = <%=raw @data%>;
0

You could try this

hash = {"people"=>111, "other"=>110}
hash.to_a.map {|k,v| [{"text" => k},{"wieght" => v}]}.flatten
=> [{"text"=>"people"}, {"wieght"=>111}, {"text"=>"other"}, {"wieght"=>110}]

1 Comment

Hash includes Enumerable so there's no need to do to_a here, and if you use flat_map instead of map you don't need flatten.
0
hash = {"people"=>111, "other"=>110}
p hash.map { |a| Hash[[:text, :weight].zip(a)] }
# => [{:text=>"people", :weight=>111}, {:text=>"other", :weight=>110}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.