如何访问块的所有者

时间:2014-01-15 21:34:10

标签: ruby

我使用

在ruby中构建了一个10x10矩阵
Matrix.build(10, 10) do 
  nil 
end.each_with_index do |e, r, c|
  # how do I get the Matrix object
end

当我遍历每个元素时,我需要知道矩阵中相邻项目中当前的内容。如何从块中获取整个Matrix对象?是否有我不知道的元变量或方法?

3 个答案:

答案 0 :(得分:4)

您可以使用tap执行此操作:

Matrix.build(10, 10) do 
  nil 
end.tap do |matrix|
  matrix.each_with_index do |e, r, c|
    # do_stuff
  end
end

但是,将中间值分配给变量通常更具可读性和惯用性,只需使用Marek suggested之类的内容,而不是让您的消息链更长。 tap很少在一些非常具体的案例之外使用,因为它几乎没有任何好处,也妨碍了可读性。

答案 1 :(得分:3)

您可以先划分代码并将新的Matrix实例分配给变量:

matrix = Matrix.build(10, 10)

然后,您可以在其上调用each_with_index并且(因为块是闭包)在传递给此方法的块内使用matrix变量。

答案 2 :(得分:1)

我会告诉你这样做如下:

Matrix.build(10, 10) do 
  nil 
end.instance_eval do
  each_with_index do |e, r, c|
    # self will automatically be set as the object on which each_with_index
    # called. Now you can use that object inside here as per your wish.
  end
end

请参阅BasicObject#instance_eval

的文档
相关问题