funfuntime
funfuntime

Reputation: 271

How to recreate .select()?

I'm trying to recreate the #select method. So far, I have array portion working, but when I try to call #my_select on a Hash, I get an empty Hash.

FYI, for starters, I had to recreate my own `#each' method. Here's that.

module Enumerable 

 def my_each
    i = 0
    while i < self.size
        yield(self[i])
        i += 1
    end
    self
 end

Now, here's the #my_select method I created:

 def my_select
    if self.instance_of?(Array)
        ret = []
        self.my_each do |item|
            ret << item if yield(item)
        end
        ret
    elsif self.instance_of?(Hash)
        ret = {}
        self.my_each do |key, value|
            if yield(key,value)
              ret[key] = value 
            end
        end
        ret
    end
  end
end

...my input/output...

> h = { "a" => 100, "b" => 200, "c" => 300 }
> h.select { |k,v| k == "a"}
=> {"a"=>100} 
> h.my_select { |k,v| k == "a"}
=> {}

Upvotes: 0

Views: 489

Answers (1)

Steve Robinson
Steve Robinson

Reputation: 3939

Maybe you could change my_each to handle Hash as well?

def my_each
    if self.instance_of?(Array)
      i = 0
      while i < self.size
          yield(self[i])
          i += 1
      end
      self
    elsif self.instance_of?(Hash)
      i = 0
      arr = self.to_a
      while i < arr.size
          yield(arr[i][0], arr[i][1])
          i += 1
      end
      self
    end
  end

Upvotes: 2

Related Questions