8

Here is my code:

class Array
    def anotherMap
         self.map {yield}
    end
end

print [1,2,3].anotherMap{|x| x}

I'm expecting to get an output of [1,2,3],but I get [nil,nil,nil]
What's wrong with my code?

3
  • What are you trying to do here? Return a new array from the current array? Commented Dec 2, 2011 at 3:23
  • 2
    BTW, the self. is superfluous Commented Dec 2, 2011 at 15:26
  • Remember to restart your server or the new method may not be available yet. Commented May 15, 2019 at 19:10

2 Answers 2

11
class Array
  def another_map(&block)
    map(&block)
  end
end
Sign up to request clarification or add additional context in comments.

Comments

9

Your code doesn't yield the value that's yielded to the block you passed to #map. You need to supply a block parameter and call yield with that parameter:

class Array
    def anotherMap
         self.map {|e| yield e }
    end
end

print [1,2,3].anotherMap{|x| x}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.