user2990614
user2990614

Reputation: 17

How to modify the class "Array" in Ruby?

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

Upvotes: 0

Views: 161

Answers (2)

sawa
sawa

Reputation: 168091

class Array
  alias filter :select
end

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

Upvotes: 2

jmromer
jmromer

Reputation: 2236

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.

Upvotes: 1

Related Questions