1

I have the following code:

class Cars
  attr_accessor :car_make
  attr_accessor :car_model
  def initialize(make, model)
    self.car_make = make
    self.car_model = model
  end
end

I would like to know if it is possible to implement a list_cars method and call the method like so:

ford = Cars.new("Ford" ,"F-150")
honda = Cars.new("Honda", "CRV")
list_cars(ford, honda)

i.e., without necessarily calling it from an existing object. I tried this:

def list_cars(first_car, second_car)
  puts "My father has two cars - a #{first_car.car_make} #{first_car.car_model} and a #{second_car.car_make} #{second_car.car_model}."
end

I realize that this code is missing something, but I don't know what that is.

4
  • Your code should work - what error are you getting? Commented Dec 5, 2015 at 15:31
  • undefined method `list_cars' for main:Object (NoMethodError) Commented Dec 5, 2015 at 15:35
  • list_cars is implemented outside class Cars right? Your code works for me. Commented Dec 5, 2015 at 15:38
  • Yep, implemented outside the class. Huh... that's weird! Commented Dec 5, 2015 at 15:44

2 Answers 2

2

Make it a class method:

class Cars
  def self.list_cars(first_car, second_car)
    puts "My father has two cars - a #{first_car.car_make} #{first_car.car_model} and a #{second_car.car_make} #{second_car.car_model}."
  end
end

Then you can call it simply by:

Cars.list_cars(car1, car2)

You can find more about class methods at rubymonk.

If this is the right way (or a new module, or as a method in object space) depends on your project architecture.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah perfect, that does it. Thanks for the tip on the resource, too - I'm teaching myself...
1

Markus's answer is the way people would normally do (and can be the preferred way since that would not pollute the main namespace). But that is not a solution to what you want. In order to do that you want, you usually implement the method on Kernel.

module Kernel
  def list_cars(first_car, second_car)
    puts "My father has two cars - a #{first_car.car_make} #{first_car.car_model} and a #{second_car.car_make} #{second_car.car_model}."
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.