Ruby在Array Class中从self获取数组参数

时间:2017-03-07 21:40:27

标签: ruby self

describe Array do
 describe "#square" do
   it "does nothing to an empty array" do
      expect([].square).to eq([])
   end

   it "returns a new array containing the squares of each element" do
      expect([1,2,3].square).to eq([1,4,9])
   end
 end
end

在此代码中,我想获取参数' [1,2,3]'。

class Array
    def square
        self
    end
end
在类Array中,如何使用' self'

获得[1,2,3]

1 个答案:

答案 0 :(得分:0)

您按原样返回self,未更改,以便您获得[1,2,3]的方式。你已经得到了你需要的东西。接下来要做些什么:

class Array
  def square
    map { |v| v ** 2 }
  end
end

map方法将一个数组转换为另一个数组。这是一个隐含的self.map