Skip to content

Instantly share code, notes, and snippets.

@peteygao
Created March 21, 2013 20:23
Show Gist options
  • Save peteygao/5216382 to your computer and use it in GitHub Desktop.
Save peteygao/5216382 to your computer and use it in GitHub Desktop.
Returning a structure like Array[Object] in Ruby
require 'ostruct'
# Given this array[hash[hash]] structure
a = [{"object" => {param1: true, param2: false}},{"object" => {param1: false, param2: true}}]
# I want to return:
=> [<OpenStruct param1=true, param2=false>, <OpenStruct param1=false, param2=true>]
# Current code:
a.map { |k| k.map { |k,v| OpenStruct.new v } }
# Returns
=> [[<OpenStruct param1=true, param2=false>], [<OpenStruct param1=false, param2=true>]]
# It's close... but I don't want the useless extra array wrapping my OStruct object.
@peteygao
Copy link
Author

Solution for those that care:
use .flatten at the end of line 10!

@peteygao
Copy link
Author

Better yet, replace line 10 with:
a.map { |k| OpenStruct.new k["object"] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment