Ruby for循环在分配数组值时给出Nil类错误

时间:2022-05-21 01:38:26

I have a problem. I'm coding up a plug in for Google Sketchup and I'm trying to filter out array value and place the filtered values into another array. This is done like this:

我有个问题。我正在为Google Sketchup编写一个插件,我正在尝试过滤掉数组值并将过滤后的值放入另一个数组中。这样做是这样的:

for z in 0..points.length
  points2[z]=points[z][1]
end

Where "points" is a double array. Can someone please tell me what I'm doing wrong?

其中“点”是双数组。有人可以告诉我我做错了什么吗?

3 个解决方案

#1


4  

This should be better:

这应该更好:

points2 = points.map {|p| p[1]}

#2


2  

What you are doing wrong is looping once to much. Using fake data:

你做错了什么就是循环一次。使用假数据:

ar = [1,2,3]
ar2 = []
for z in 0..ar.length 
#off by one! Should be one less. But then you should test for empty arrays...
  ar2[z] = ar[z]
end
p ar2 #[1, 2, 3, nil]

The other answers advocate map and they are right, but you could transform the for-loop into a less error-prone one like this:

其他答案提倡地图,他们是正确的,但你可以将for-loop转换为一个不那么容易出错的地图,如下所示:

for z in ar
  ar2 << z
end

#3


1  

What you are doing wrong? Fan of for loop that I am, you should use functional style, aka. Ruby way:

你做错了什么?我是for循环的粉丝,你应该使用功能风格,又名。 Ruby方式:

points2 = points.map { |element| element[1] }

Otherwise, you would have to post better example if you want people to diagnose your for loop.

否则,如果您希望人们诊断您的for循环,则必须发布更好的示例。

#1


4  

This should be better:

这应该更好:

points2 = points.map {|p| p[1]}

#2


2  

What you are doing wrong is looping once to much. Using fake data:

你做错了什么就是循环一次。使用假数据:

ar = [1,2,3]
ar2 = []
for z in 0..ar.length 
#off by one! Should be one less. But then you should test for empty arrays...
  ar2[z] = ar[z]
end
p ar2 #[1, 2, 3, nil]

The other answers advocate map and they are right, but you could transform the for-loop into a less error-prone one like this:

其他答案提倡地图,他们是正确的,但你可以将for-loop转换为一个不那么容易出错的地图,如下所示:

for z in ar
  ar2 << z
end

#3


1  

What you are doing wrong? Fan of for loop that I am, you should use functional style, aka. Ruby way:

你做错了什么?我是for循环的粉丝,你应该使用功能风格,又名。 Ruby方式:

points2 = points.map { |element| element[1] }

Otherwise, you would have to post better example if you want people to diagnose your for loop.

否则,如果您希望人们诊断您的for循环,则必须发布更好的示例。