猴子补丁和RSpec

时间:2014-10-09 22:02:19

标签: ruby rspec

我在我的课程中遇到了Block checkpoint,我必须让它通过rspec才能继续前进。猴子修补(到目前为止,我讨厌它,哈哈)阻碍我完成阻止,我知道这是错的,但我会发布我所拥有的,也许我可以最终提交这个,然后转移到每个索引。这就是我几周前的情况,我确信这太复杂了。

首先是规格

describe Array do
  describe '#new_map' do
    it "returns an array with updated values" do
      array = [1,2,3,4]
      expect( array.new_map(&:to_s) ).to eq( %w{1 2 3 4} )
      expect( array.new_map{ |e| e + 2 } ).to eq( [3, 4, 5, 6] )
    end

    it "does not call #map" do
      array = [1,2,3,4]
      array.stub(:map) { '' }
      expect( array.new_map(&:to_s) ).to eq( %w{1 2 3 4} )
    end

    it "does not change the original array" do
      array = [1,2,3,4]
      expect( array.new_map(&:to_s) ).to eq( %w{1 2 3 4} )
      expect( array ).to eq([1,2,3,4])
    end
  end

  describe '#new_select!' do
    it "selects according to the block instructions" do
      expect( [1,2,3,4].new_select!{ |e| e > 2 } ).to eq( [3,4] )
      expect( [1,2,3,4].new_select!{ |e| e < 2 } ).to eq( [1] )
    end

    it "mutates the original collection" do
      array = [1,2,3,4]
      array.new_select!(&:even?)
      expect(array).to eq([2,4])
    end
  end
end

describe String do 
  describe "collapse" do
    it "gets rid of them white spaces" do
      s = "I am a white spacey   string"
      expect(s.collapse).to eq("Iamawhitespaceystring")
    end

    it "doesn't mutate" do
      s = "I am a white spacey   string"
      s.collapse
      expect(s).to eq("I am a white spacey   string")
    end
  end

  describe "collapse!" do
    it "mutates the original string" do
      s = "I am a white spacey   string"
      s.collapse!
      expect(s).to eq"Iamawhitespaceystring"
    end
  end
end

这就是我输入的内容:

class Array
  def new_map(&block)
    self.replace(self.map(&block))
  end

  def new_select!(&block)
    self.replace(self.map(&block))
    #[1,2,3,4].new_select!{ |e| e > 2 } )=(&block)
  end
end

class String
  def collapse
    s = "I am a white spacey  string".delete(' ') 


  end

  def collapse!

    s.delete('+') 

   end

end

到目前为止,我只能让String崩溃摆脱它们的空格并且String collapse不会变异传递

1 个答案:

答案 0 :(得分:3)

收到帮助并通过了:

class Array
  def new_map
    new_array = []
    each do |item|
      new_array << yield(item)
    end
    new_array
  end

  def new_select!(&block)
    replace( select(&block) )
  end
end

class String
  def collapse
    split.join
  end

  def collapse!
    replace( collapse )
  end
end