Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top