View an object with Ruby on Rails

advertisements

I have some JSON that looks like this. I have it stored and read into an object, @items.

[
 {
  {
    "id": "A",
    "description": "a_description"
  },
  {
    "id": "B",
    "description": "b_description"
  }
 },
 {
  {
    "id": "A",
    "description": "a_description"
  },
  {
    "id": "B",
    "description": "b_description"
  }
 }
]

My goal is to display a table with two columns, one labeled A and the other labeled B, in which each row gives the "a_description" and "b_description". I'm not sure how to go about doing this.


Ah, the ol' array of hashes and hashes of arrays problem.

To get around your "out of order" problem you first have to convert

{
  "id": "A",
  "description": "foo"
},
{
  "id": "B",
  "description": "bar"
}

into {"A" : "foo", "B" : "bar" }.

@new_items = @items.map do |item|
  output = {}
  item.each do |hash|
    output.merge!(hash["id"] => hash["description"])
  end
end

Then @new_items becomes (intentionally presented out of order since hash elements are not ordered)

[
  {
    "A": "a1_description",
    "B": "b1_description"
  },
  {
    "B": "b2_description",
    "A": "a2_description"
  }
]

From there, each line is simply a hash, so you can just dereference the value you need based on the column you're in.

@new_items.each do |item|
  puts "#{item['A']} is paired with #{item['B']}"
end

Keys, of course could be retrieved dynamically if you don't want to hard code "A" and "B" using .keys