omgmakeme
omgmakeme

Reputation: 766

Creating custom methods

What is best practice / syntax for trying to extract internal methods within a class?

class Foo

  def initialize
  end

  def get_value
    array = (API CALL TO GET ARRAY)
    array.array_lookup("Bar")
  end

  def array_lookup(query)
    self.each do |hash|
      if hash[:key] == query
         p hash[:value]
      end
    end
  end

end

foo = Foo.new
foo.get_value #=> : undefined method `array_lookup' for #<Array:0x007fd3a49a2ca0 (NoMethodError)

The error message is telling me that my array object doesn't know how to respond to my method which makes sense in that I have an array that doesn't have this method, though I'm wondering how to fix this and similar uses. Do I overwrite the array class? Do I change my self.syntax?

Upvotes: 0

Views: 103

Answers (2)

Dave N
Dave N

Reputation: 398

How about something like this? You turn your custom object into a subclass of Array so you get the array methods like #each. Actually, come to think of it, a better implementation might include mixing in the Enumerable module into your custom class (thinking composition over inheritance).

class Foo < Array
  # More robust to change in application if you allow passing
  # the query into this method. Just a suggestion.
  def get_value(query)
    request_data
    lookup(query)
  end

protected

  def request_data
    # API call to get data, assume this is array with contents
    data = []
    # Set contents of this object to contents of returned array
    replace(data)
  end

  def lookup(query)
    each do |hash|
      if hash[:key] == query
        puts hash[:value]
      end
    end
  end
end

foo = Foo.new
foo.get_value("BAR")

Upvotes: 0

shirakia
shirakia

Reputation: 2409

array_lookup is Foo's method. So inside Foo class, you can call it by

array_lookup("Bar")

(without array.)

Upvotes: 1

Related Questions