small medium large xlarge

Img_0373_pragsmall
11 Aug 2010, 21:32
John Burnaman (2 posts)

In the introduction to Ruby section which covers classes, there is a class method example:

 ...
 def self.find_all_unpaid
      self.where('paid=0')
 end
 ...

A bit later in the text, we are given the example of calling this method:

 to_collect = Order.find_all_unpaid

If I’m following this, a class method would fire for each instance of the Order object, but I am unclear on how the method structures the return value in this particular case. If I understand correctly, each method without a specified return value returns the last expression evaluated.

Would the result here be an array or a hash of each instance that meets the conditions set in the method?

Samr_small_pragsmall
12 Aug 2010, 01:48
Sam Ruby (634 posts)

Your final answer is essentially correct.

Order.find_all_unpaid doesn’t fire a method for each instance, it fires a single method. In this case a class method. Inside an instance method, ‘self’ refers to the instance. Inside a class method, ‘sef’ refers to the class.

So, in the above,

to_collect = Order.find_all_unpaid

… is equivalent to:

to_collect = Order.where('paid=0')

The ‘where’ method is defined elsewhere, but will ultimately result in returning

ActiveRecord (the superclass of Order) provides a ‘where’ method. That method will return an object that can be used to iterate over the orders that match the condition specified. That object isn’t actually a hash or array, it is an ActiveRecord::Relation, but instances of that class do behave very much like an arrays.

You must be logged in to comment