Ask coding questions

← Back to all posts
Object on object interaction in Ruby - How to do it?

Hello, I can't find a clear guide or answer on how to achieve this in Ruby - I have previously done it using Java.

I am wondering how to make objects interact directly by using object parameters in their methods. For the attached example, two 'dogs' are instantiated. I want dog1 to call its 'attack' method on another dog (dog2), and result this in that objects 'health' being reduced by 10. I have coded this as dog1.attack(dog2) but as expected it doesn't work.

Beyond this, how to make objects of separate classes interact in the same way. For example, in Java I created a basic app where a 'Garden' object had its grass cut by a 'Gardener' object of a different class - gardener.cutGrass(garden1).

The use of declared types as parameters etc. in Java makes this fairly easy - what is the equivalent in Ruby? Thanks!