[英]How to initialise multiple array in single line in Ruby?
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?
但是如果我像这样返回它 [], [] 它给出错误,而如果我像返回它 [[],[]] 它工作正常但在后一种情况下,3 arrays 将得到我想要的初始化避免? Is there any better way to do it using 2 array itself?
有没有更好的方法来使用 2 数组本身?
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
if I return it like
[[],[]]
it is working fine but in the later case, 3 arrays will get initialize which I want to avoid?如果我像
[[],[]]
一样返回它,它工作正常,但在后一种情况下,3 arrays 将得到我想要避免的初始化?
It cannot be avoided because a method can only return a single object.这是无法避免的,因为一个方法只能返回一个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
Use return in front,在前面使用 return,
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.