...

/

Interacting Objects

Interacting Objects

Learn how objects interact with each other in Ruby.

We’re now able to create our own objects. However, they don’t do a whole lot, yet, right? Why not create two people, and let them greet each other.

Let’s see.

Here’s what we’d like to achieve:

Press + to interact
class Person
def initialize(name)
@name = name
end
def name
@name
end
end
person = Person.new("Anja")
friend = Person.new("Carla")
person.greet(friend)

We’d like this to print out the following for starters:

Hi Carla!

If we run the code above we’ll get an error message that tells us what to do next:

NoMethodError: undefined method `greet' for #<Person:0x007fbb5e9c88c8 @name="Anja">

Right, we need to define a method greet. Let’s do that:

Press + to interact
class Person
# methods from above ...
def initialize(name)
@name = name
end
def name
@name
end
#Now,
def greet
end
end
person = Person.new("Anja")
friend = Person.new("Carla")
person.greet(friend)

If we run this code, we’ll now get a new error message. Great, that’s progress:

ArgumentError: wrong number of arguments (1 for 0)
...

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy