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.

0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

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?
if you want to add, it will be obj_hash[obj.group_id] << obj (previously you have to initialize the array)
I tried that before using group_by, but would get the error: NoMethodError: undefined method `<<' for nil:NilClass. Any idea why?
as I said, you have to initialize the array. otherwise it will be Nil: obj_hash[obj.group_id] ||= []
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 }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.