0

I'm new about ruby! I just wanna do the following:

module Functional
  def filter
  end
end

class Array
  include Functional
  def filter
  end
end

a = [1, -2, 3, 7, 8]
puts a.filter{|x| x>0}.inspect      # ==>Prints out positive numbers

How could I modify the method "filter" in Array? Could anybody help me? Thank you

2
  • 2
    That works for me. Prints out nil as expected Commented Nov 14, 2013 at 5:23
  • Try to create a reproduction test-case on ideone.com or similar (against a specific Ruby version, ideone is currently Ruby 1.9.3) so the behavior can be verified - for instance, when I try, I get nil as output . Counterexample? :) Commented Nov 14, 2013 at 5:25

2 Answers 2

2
class Array
  alias filter :select
end

a = [1, -2, 3, 7, 8]
a.filter{|x| x > 0}
Sign up to request clarification or add additional context in comments.

Comments

1

I think what you're looking for is this:

module Functional
  def filter
    return self.select{ |i| i > 0 }
  end
end

class Array
  include Functional
end

a = [1, -2, 3, 7, 8]
puts a.filter{|x| x>0}.inspect      
#=>[1, 3, 7, 8]

Although I think you can save yourself the trouble by just using select -- there's no need to reimplement it.

1 Comment

Oh, the comment was what OP wanted to do, not what OP was seeing and wondering why it wasn't being re-defined.

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.