How to initialise multiple array in single line in Ruby?

318 Views Asked by At

I'm trying to do some calculations and get the groups and departments array from there. but if I'm returning it like this [], [] It is giving error, while if I return it like [[],[]] it is working fine but in the later case, 3 arrays will get initialize which I want to avoid? Is there any better way to do it using 2 array itself?

    def fetch_group_dept_values
      if condition
        [1,2,3,], [4,5]
      else  
        [9,15], [10,11]
      end
    end

    groups, departments = fetch_group_dept_values 

2

There are 2 best solutions below

5
Stefan On BEST ANSWER

if I return it like [[],[]] it is working fine but in the later case, 3 arrays will get initialize which I want to avoid?

It cannot be avoided because a method can only return a single object.

So wrapping the objects in [...] is just fine:

def fetch_group_dept_values
  if condition
    [[1, 2, 3,], [4, 5]]
  else  
    [[9, 15], [10, 11]]
  end
end

The overhead of creating a (small) extra array is negligible.

However, you could avoid the outer array by yielding the values instead of returning them:

def fetch_group_dept_values
  if condition
    yield [1, 2, 3,], [4, 5]
  else  
    yield [9, 15], [10, 11]
  end
end

And call it via:

fetch_group_dept_values do |groups, departments|
  # ...
end
1
shailjakant On

Use return in front,

   def fetch_group_dept_values
      if condition
        return [1,2,3,], [4,5]
      else  
        return [9,15], [10,11]
      end
    end

    groups, departments = fetch_group_dept_values