Ryan Glass Ryan Glass - 1 month ago 8
Ruby Question

Array not saving user input in ruby

This is what I have so far, but the array is not saving the first value if the user enters 2 or more car types. If I remove the car.get_ methods the program runs fine without saving the users input. Is there a method I am missing?

class Cars

def set_make(make)
end

def set_model(model)
end

def set_year(year)
end

array_of_cars = Array.new

print "How many cars do you want to create? "
num_cars = gets.to_i
puts

for i in 1.. num_cars
puts
print "Enter make for car #{i}: "
make = gets.chomp

print "Enter model for car #{i}: "
model = gets.chomp

print "Enter year of car #{i}: "
year = gets.to_i

c = Car.new

c.set_make(make)
c.set_model(model)
c.set_year(year)

array_of_cars << c
end

puts
puts "You have the following cars: "

for car in array_of_cars
print "#{car.get_year} #{car.get_make} #{car.get_model}"
end
end

Answer

Ok so the primary issue is that you calling the Car.new where the Car class is defined. You should not have an array of cars in the car class. You could try creating a Dealership class that has an array of cars then you could do something like this

class Dealership

  attr_accessor :car_lot

  def initialize
    @car_lot = []
  end

  def add_car(car)
    @car_lot << car
  end
end
crazy_carls = Dealership.new
car1 = Car.new(make, model, year)

crazy_carls.add_car(car1)
crazy_carls.car_lot.each do |car
  print "#{car.get_year} #{car.get_make} #{car.get_model}"
end

You need to refactor the car class a good deal first though, look into how to use the initialize method, attr_accessor, and instance variables.

Comments