简体   繁体   中英

Ruby (Monkey Patching Array)

Back for more help on my coursework at Bloc. Decided to bring you guys in on a problem I'm having with Monkey Patching the Array Class. This assignment had 8 specs to be met and I'm stuck now with one left and I'm not sure what to do.

I'm only going to give you the RSpecs and written requirements for the part that I'm having trouble w/ since everything else seems to be passing. Also I'll include the starter scaffolding that they gave me to begin with so there's no confusion or useless additions to the code.


Here are the written requirements for the Array Class Monkey Patch:

  • Write a new new_map method that is called on an instance of the Array class. It should use the array it's called on as an implicit ( self ) argument, but otherwise behave identically. ( INCOMPLETE )

  • Write a new_select! method that behaves like the select, but mutates the array on which it's called. It can use Ruby's built-in collection select method. ( COMPLETE )


Here are the RSpecs that need to be met regarding the Array class:

Note: "returns an array with updated values" Is the only Spec not passing.

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

Here is the scaffolding they started me with:

class Array
  def new_map
  end

  def new_select!(&block)
  end
end

Lastly, here is my code:

class Array
  def new_map 
    new_array = []
    self.each do |num|
      new_array << num.to_s
    end
    new_array
  end

  def new_select!(&block)
    self.select!(&block)
  end
end

Ruby Array Class:

 map { |item| block } → new_ary 

A block is like a method, and you specify a block after a method call, for example:

[1, 2, 3].map() {|x| x*2} #<---block
           ^
           |
       method call(usually written without the trailing parentheses)

The block is implicitly sent to the method, and inside the method you can call the block with yield .

yield -> calls the block specified after a method call. In ruby, yield is equivalent to yield() , which is conceptually equivalent to calling the block like this: block() .

yield(x) -> calls the block specified after a method call sending it the argument x, which is conceptually equivalent to calling the block like this: block(x) .

So, here is how you can implement new_map():

class Array
  def new_map
    result = []

    each do |item|
      result << yield(item)
    end

    result

  end
end

arr = [1, 2, 3].new_map {|x| x*2}
p arr

--output:--
[2, 4, 6]

This comment is a bit advanced, but you don't actually have to write self.each() to call the each() method inside new_map(). All methods are called by some object, ie the object to the left of the dot, which is called the receiver . For instance, when you write:

self.each {....}

self is the receiver of the method call each().

If you do not specify a receiver and just write:

each {....}

...then for the receiver ruby uses whatever object is assigned to the self variable at that moment. Inside new_map() above, ruby will assign the Array that calls the new_map() method to self, so each() will step through the items in that Array.

You have to be a little bit careful with the self variable because ruby constantly changes the value of the self variable without telling you. So, you have to know what ruby has assigned to the self variable at any particular point in your code--which comes with experience. Although, if you ever want to know what object ruby has assigned to self at some particular point in your code, you can simply write:

puts self

Experienced rubyists will crow and cluck their tongues if they see you write self.each {...} inside new_map(), but in my opinion code clarity trumps code trickiness , and because it makes more sense to beginners to write self there, go ahead and do it. When you get a little more experience and want to show off, then you can eliminate explicit receivers when they aren't required. It's sort of the same situation with explicit returns:

def some_method
    ...
    return result
end

and implicit returns:

def some_method
    ...
    result
end

Note that you could write new_map() like this:

class Array
  def new_map(&my_block)  #capture the block in a variable
    result = []

    each do |item|
      result << my_block.call(item) #call the block
    end

    result

  end
end

arr = [1, 2, 3].new_map {|x| x*2}
p arr

--output:--
[2, 4, 6]

Compare that to the example that uses yield(). When you use yield(), it's as if ruby creates a parameter variable named yield for you in order to capture the block. However, with yield you use a different syntax to call the block, namely () , or if their are no arguments for the block, you can eliminate the parentheses--just like you can when you call a method. On the other hand, when you create your own parameter variable to capture a block, eg def new_map(&my_block) , you have to use a different syntax to call the block:

  1. my_block.call(arg1, ...)

or:

  1. myblock[arg1, ...]

Note that #2 is just like the syntax for calling a method--except that you substitute [] in place of () .

Once again, experienced rubyists will use yield to call the block instead of capturing the block in a parameter variable. However, there are situations where you will need to capture the block in a parameter variable, eg if you want to pass the block to yet another method.

Looking at the spec here:

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 looks like they just want you to re-write Array.map so that it will work with any given block. In your implementation you are telling the method to work in a very specific way, namely to call .to_s on all of the array elements. But you don't want it to always stringify the array elements. You want it to do to each element whatever block is provided when the method is called. Try this:

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

Notice in my example that the method definition doesn't specify any particular operation to be performed on each element of self . It simply loops over each element of the array, yields the element ( num ) to whatever block was passed when .new_map was called, and shovels the result into the new_array variable.

With that implementation of .new_map and given array = [1,2,3,4] , you can call either array.new_map(&:to_s) ( the block is where the arbitrary operation to be performed on each element of the array is specified) and get ["1","2","3","4"] or you can call array.new_map { |e| e + 2 } array.new_map { |e| e + 2 } and get [3,4,5,6] .

I would like to say a few words about new_select! .

select vs select!

You have:

class Array
  def new_select!(&block)
    self.select!(&block)
  end
end

which you could instead write:

class Array
  def new_select!
    self.select! { |e| yield(e) }
  end
end

This uses the method Array#select! . You said Array#select could be used, but made no mention of select! . If you cannot use select! , you must do something like this:

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

Let's try it:

a = [1,2,3,4,5]
a.new_select! { |n| n.odd? }
  #=> [1, 3, 5] 
a #=> [1, 3, 5] 

Explicit vs implicit receivers

Notice that I have written this without any explicit receivers for the methods Array#replace and Array#select . When there is no explicit receiver, Ruby assumes that it is self , which is the a . Therefore, Ruby evaluates replace(select(&block)) as though it were written with explicit receivers:

self.replace(self.select(&block)) 

It's up to you to decide if you want to include self. . Some Rubiests do, some don't. You'll notice that self. is not included in Ruby built-in methods implemented in Ruby. One other thing: self. is required in some situations to avoid ambiguity. For example, if taco= is the setter for an instance variable @taco , you must write self.taco = 7 to tell Ruby you are referring to the setter method. If you write taco = 7 , Ruby will assume you want to create a local variable taco and set its value to 7.

Two forms of select!

Is your method new_select! a direct replacement for select! ? That is, are the two methods functionally equivalent? If you look at the docs for Array#select! , you will see it has two forms, the one you have mimicked, and another that you have not implemented.

If select! is not given a block, it returns an enumerator. Now why would you want to do that? Suppose you wish to write:

a = [1,2,3,4,5]
a.select!.with_index { |n,i| i < 2 }
  #=> [1, 2] 

Has select! been given a block? No, so it must return an enumerator, which becomes the receiver of the method Enumerator#with_index .

Let's try it:

enum0 = a.select!
  #=> #<Enumerator: [1, 2, 3, 4, 5]:select!>

Now:

enum1 = enum0.with_index
  #=> #<Enumerator: #<Enumerator: [1, 2, 3, 4, 5]:select!>:with_index> 

You can think of enum1 as a "compound enumerator". Look carefully at the description (above) of the object Ruby returns when you define enum1 .

We can see the elements of the enumerator by converting it to an array:

enum1.to_a
  # => [[1, 0], [2, 1], [3, 2], [4, 3], [5, 4]]

Each of these five elements is passed to the block and assigned to the block variables by Enumerator#each (which calls Array#each ).

Enough of that, but the point is that having methods return enumerators when no block is given is what allows us to chain methods.

You do not have a test that ensures new_select! returns an enumerator when no block is given, so maybe that's not expected, but why not give it a go?

class Array
  def new_select!(&block)
    if block_given?
      replace(select(&block))
    else
      to_enum(:new_select!)
    end
  end
end

Try it:

a = [1,2,3,4,5]
a.new_select! { |n| n.odd? }
  #=> [1, 3, 5] 
a #=> [1, 3, 5] 

a = [1,2,3,4,5]
enum2 = a.new_select!
  #=> #<Enumerator: [1, 2, 3, 4, 5]:new_select!> 
enum2.each { |n| n.odd? }
  #=> [1, 3, 5] 
a #=> [1, 3, 5]

a = [1,2,3,4,5]
enum2 = a.new_select!
  #=> #<Enumerator: [1, 2, 3, 4, 5]:new_select!> 
enum2.with_index.each { |n,i| i>2 }
  #=> [4, 5] 
a #=> [4, 5] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM