[Courses] [Ruby] Lesson 1: Classes
Laurel Fan
laurel.fan at gmail.com
Sun Nov 27 07:07:51 EST 2005
On 11/26/05, Anne G <anne at wjh.harvard.edu> wrote:
> I can't find any information about how to have objects
> interact.
>
> Most of the examples are about sending a method to an object
> from the program. I can't find an example of an object
> sending a message to an other object.
>
> How do you get an object to send a message to an other
> object given that the objects don't yet exist when the
> classes and instance method are defined in the code?
I'm not quite clear on what you're asking, but I think you might be
over thinking it a little. The other objects don't need to exist when
you are defining the methods, only when the method is actually called.
Methods can call methods on other objects pretty much whenever they
feel like. Let's say I'm writing a program to control my smart
fridge.
class Fridge
def init
@milk_cartons = Array.new()
end
def add_milk_carton(carton)
@milk_cartons.add
end
def has_milk?
@milk_cartons.each do |carton|
if !carton.empty?
return true
end
end
false
end
end
In this case, the has_milk? function sends a message to the object
that we're using to represent milk cartons. We haven't defined that
object yet, but as long as it's defined by the time we run the program
and call the function, it'll work fine.
This is something that's mostly unique to ruby: Most of the time, it
doesn't matter what the actual type/class of an object is. It only
matters what methods it responds to. For example, in this case, we
could define a new MilkCarton class that implements the empty? method,
but if we're feeling lazy we could use a String (since String
implements empty? as well).
There's even a special method called method_missing that is called on
an object when we try to send it a message (ie. call a method) that it
doesn't understand. This lets you implement methods without actually
implementing them. The book has a toy example of what you can do with
this:
http://www.rubycentral.com/book/ref_c_object.html#Object.method_missing
Thanks for all of your questions (let me know if this wasn't clear or
didn't answer your question)!
--
Laurel Fan
http://dreadnought.gorgorg.org
More information about the Courses
mailing list