Ruby从数组类中的self获取数组参数

Ruby从数组类中的self获取数组参数,ruby,self,Ruby,Self,在这段代码中,我想得到参数“[1,2,3]” 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

在这段代码中,我想得到参数“[1,2,3]”

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

在类数组中,如何使用“self”获取[1,2,3]?

您将按原样返回
self
,因此这就是如何获取
[1,2,3]
。你已经得到你需要的了。下一步是用它做点什么:

class Array
    def square
        self
    end
end

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

self
已经引用了数组对象,您当前的代码看起来是正确的,只是没有将数组
self
的元素平方。数组就是你正在处理的实例。哦,我明白了。非常感谢!:-)
class Array
  def square
    map { |v| v ** 2 }
  end
end