I have written the following code in Ruby that takes input from a user regarding plane and flight details and displays the user inputs as an array in the terminal. For example, if the user enters 3 then the program reads in input 3 times. However, I am getting the following error but I am not sure why: Traceback (most recent call last):
2: from plane.rb:68:in <main>' 1: from plane.rb:65:in main’
plane.rb:56:in print_planes': undefined method length’ for nil:NilClass (NoMethodError)
Blockquote
require ‘./input_functions’
class Plane
attr_accessor :id, :number, :origin, :destination
def initialize (id, number, origin, destination)
@id=id
@number = number
@origin = origin
@destination = destination
end
def read_planes()
planes=Array.new()
planes_count = read_integer(“How many planes are you entering?”)
count=0
while (count<planes_count)
planes<<read_plane()
count+=1
end
Thank you for your reply, pcl. I have put in the return statement as you suggested. But instead of the program printing out the user input in the terminal I am getting this “#Plane:0x0000557c9678a880”. Why is this happening?
Hi, pcl
Thank you for replying again. I have tried doing as you suggested by doing the following:
def print_planes(planes)
index = 0
while (index<planes.length)
print_plane
index+=1
end
But I now get an argument error. I am still very new to ruby so I can’t figure out how to fix this.
But I now get an argument error. I am still very new to ruby so I can’t figure out how to fix this.
Take it step by step: What does your print_plane method do? It takes a plane as an argument, and prints its details.
What does your print_planes method do? It takes a list of planes as an argument, looks at each one, and prints its details, by calling print_plane. index is used to refer to each plane in turn, and planes[index] is the current plane.
What are you missing? You have not passed the current plane to print_plane - you were almost there with puts planes[index], instead write:
print_plane planes[index]
You will run into a new problem here: because the @id is an integer, it can’t be printed directly but must be converted into a string. You can add to_s to each line in print_plane, like below:
puts ("Plane id "+plane.id.to_s)
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.