1

I'm a bit fuzzy on how to work with multidimensional arrays in Ruby. How would I recreate this PHP code in Ruby?

$objs_array = array();
foreach($objs AS $obj) {
    $objs_array[$obj->group_id][] = $obj;
    }
}
print_r($objs_array);

The result would be:

Array
(
    [123] => Array
        (
            [0] => Array
                (
                    object1
                )
            [1] => Array
                (
                    object2
                )
        )
    [456] => Array
        (
            [0] => Array
                (
                    object3
                )
            [1] => Array
                (
                    object4
                )
        )
)

Thanks.

Slowfib
  • 291
  • 1
  • 4
  • 15

2 Answers2

2

More than a multidimensional array, hash of arrays would fit better.

In php you only have the type array, but in ruby the class Hash is very useful

objs_hash = {}
objs.each do |obj|
    objs_hash[obj.id] = obj
end
rhernando
  • 1,051
  • 7
  • 18
  • Thanks! Very close, but this: 'objs_hash[obj.id] = obj' will overwrite the hash with another obj that shares the ID, right? It might be more clear on what I'm trying to do if you replace obj.id with obj.group_id. In PHP, I would do: '[obj.group_id][]' to add to the array. How would you do that in Ruby? – Slowfib Feb 05 '14 at 04:38
  • if you want to add, it will be obj_hash[obj.group_id] << obj (previously you have to initialize the array) – rhernando Feb 06 '14 at 15:06
  • I tried that before using group_by, but would get the error: NoMethodError: undefined method `<<' for nil:NilClass. Any idea why? – Slowfib Feb 06 '14 at 23:57
  • as I said, you have to initialize the array. otherwise it will be Nil: obj_hash[obj.group_id] ||= [] – rhernando Feb 09 '14 at 21:22
0

Thank you rhernado for sending me down the road of looking into hashes. I ended up finding a similar question that pointed out the group_by method: Building Hash by grouping array of objects based on a property of the items - I ended up using a hash of an array of objects by using:

groups = objs.group_by { |obj| obj.group_id }
Community
  • 1
  • 1
Slowfib
  • 291
  • 1
  • 4
  • 15