3

There is 'groups' hash, when key of the hash is name of some group, and value of the hash is an array of some items. I want to encode it into JSON, but I can't event encode name of key in hash, because it's not contanstant:

x = Jbuilder.encode do |json|
  groups.each do |k, v|     
    json.set!(:group, k)
    json.group k    
  end
end

May be you suggest me how to execute method of 'json' using dynamic name?

1 Answer 1

4

Use the array! method:

json.array!(groups) do |json, group|
    json.set!(group.name, array)
end

Edit: For a hash of groups with each group's name as its key, do this:

groups.each do |group|
    json.set!(group.name, array)
end
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is wrong, I need to render hash of arrays: { "type1": [...], "type2": [...] }. Can you make some example?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.