我想在Ruby中使用块,我有这样的代码:如何在Ruby中使用与块
def positions
return horizontally_position if orientation == "horizontally"
vertically_position
end
def horizontally_position
res = []
for x in position[0]..end_coord(0)
res << [x, position[1]]
end
return res
end
def vertically_position
res = []
for y in position[1]..end_coord(1)
res << [position[0], y]
end
return res
end
似乎有重复的代码,并且希望使用一个块或一个产量提高性能,但不知道如何!
这样做:
def positions
return h_v_position(0, {[x, position[1]]}) if orientation == "horizontally"
h_v_position(1, {[position[0], y]})
end
def h_v_positions(coord, &block)
res = []
for x in position[coord]..end_coord(coord)
res << block.call
end
return res
end
但没有工作..有没有帮助?
如果我要解释这个权利,我觉得强似块,你只是想通过阵列'[X,位置[1]'或'[位置[0],Y]'。另外,在Ruby中使用块时,可以像传递参数那样传递参数,但在方法内部,您可以使用'block.call'调用块。但是,块是块。它们就是那些用来传递特定参数给使用方法的'{stuff in here}'。但是,就你而言,它看起来像是将数组中的信息传递给另一个名为'res'的数组,并将其返回。 –
谢谢你,我找到了解决方案,我会在几分钟后发布。 –