Here when we print array elements it display null value all time like "[nil, nil, nil, nil]"
Values are not getting stored in array.
class Flight
def initilize(flight_id, flight_num, flight_orgin, flight_destination)
#id= flight_id
#number = flight_number
#origin = flight_origin
#destination = flight_destination
end
def read_flight()
puts "enter flight id"
flight_id = gets.chomp
puts "enter flight number"
flight_number = gets.chomp
puts "enter flight origin location"
flight_origin = gets.chomp
puts "enter destination"
flight_destination = gets.chomp
end
def print_flight(id, number, orgin, destination)
puts "_____Flight details______"
puts "Flight_id :#{id}"
puts "Flight_number :#{number}"
puts "Flight_orgin :#{orgin}"
puts "Flight_destination:#{destination}"
end
def read_flights(id, number, orgin, destination)
puts "_______Array of flights______"
flightid = Array.new
flightid.push(id, number, orgin, destination)
puts "#{flightid}"
end
end
input_flight = Flight.new
input_flight.read_flight
input_flight.print_flight(#id, #num, #orgin, #destination)
input_flight.read_flights(#id, #num, #orgin, #destination)
Without using a class or instance variable we want to do it
User input
enter flight id
2
enter flight number
2342
enter flight origin location
cochin
enter destination
tvm
output
Flight details_
Flight_id :
Flight_number :
Flight_orgin :
Flight_destination:
_Array of flights
[nil, nil, nil, nil]
The #id, #num, #orgin, #destination parameters will be nil if you don't set them anywhere.
So when you make these two calls:
input_flight.print_flight(#id, #num, #orgin, #destination)
input_flight.read_flights(#id, #num, #orgin, #destination)
You basically just send nils into the function:
input_flight.print_flight(nil, nil, nil, nil)
input_flight.read_flights(nil, nil, nil, nil)
If you want to access the variables read from the input:
First, you need to store them somewhere. For ex: store them inside the instance variables when read_flight function is called.
Then, refer the instance variable when you want to push values in the array.
Ex:
def read_flight
puts "enter flight id"
#id = gets.chomp # store inside instance variable
puts "enter flight number"
#number = gets.chomp
puts "enter flight origin location"
#origin = gets.chomp
puts "enter destination"
#destination = gets.chomp
end
def read_flights
...
flightid.push(#id, #number, #origin, #destination) # access instance variables here
...
end
You can learn more about Ruby's variable scoping (instance variables, global variables, etc) here: https://www.techotopia.com/index.php/Ruby_Variable_Scope
Here is my version of adjustion:
class Flight
attr_reader :id, :number, :origin, :destination
def read_flight
puts "enter flight id"
#id = gets.chomp
puts "enter flight number"
#number = gets.chomp
puts "enter flight origin location"
#origin = gets.chomp
puts "enter destination"
#destination = gets.chomp
end
def print_flight
puts "_____Flight details______"
puts "Flight_id :#{id}"
puts "Flight_number :#{number}"
puts "Flight_orgin :#{origin}"
puts "Flight_destination:#{destination}"
end
def read_flights
puts "_______Array of flights______"
flightid = [id, number, origin, destination]
puts "#{flightid}"
end
end
input_flight = Flight.new
input_flight.read_flight
input_flight.print_flight
input_flight.read_flights
Explanation:
Each instance of ruby class can have as many instance variables (which begin with #) as possible. Those instance variables live in an instance so they keep their value across the methods.
So you should assign the value you want to instance variables, for example:
#id = gets.chomp
then use it in another method:
def print_flight
puts "_____Flight details______"
puts "Flight_id :#{#id}"
end
However, add # everytime we want to use the instance variables is pretty tedious. That's why attr_reader comes in. When you write attr_reader:
attr_reader :id, :number, :origin, :destination
You actually declare 4 methods inside Flight:
def id
#id
end
def number
#number
end
def origin
#origin
end
def destination
#destination
end
Then you can just use id, number, origin, destination without the leading #`
You're initializing with nil values in your constructor (def initialize), to fix that you can pass the values to the .new or change the read_flight as follows:
def read_flight()
puts "enter flight id"
#flight_id = gets.chomp
puts "enter flight number"
#flight_number = gets.chomp
puts "enter flight origin location"
#flight_origin = gets.chomp
puts "enter destination"
#flight_destination = gets.chomp
end
This will modify the class-scoped variables.
Or alternatively you can have default values in the constructor (not recommended) using the || operator:
def initilize(flight_id, flight_num, flight_orgin, flight_destination)
#id= flight_id || 0
#number = flight_number || 0
#origin = flight_origin || ""
#destination = flight_destination || ""
end
First of all, be careful, because you did a lot of little but important mistakes. It's ok, we all started like that)
For example, your 'initialize' method name is not correct!
Your: 'initilize'
Correct: 'initialize'
It's important to name default methods correct.
Also, when you initialize variables with method arguments:
def initilize(flight_id, flight_num, flight_orgin, flight_destination)
#id= flight_id
#number = flight_num #you have to name it just like argument in method not flight_number, because it does not exist at all
#origin = flight_origin #same here, you forgot one letter
#destination = flight_destination
end
If you want user to initialize your instances then don't initialize them by yourself, delete arguments in initialize method.
Also, you can use instance variables in entire class, it's really helpful!
So, i corrected a little:
class Flight
def read_flight
puts "enter flight id"
#id = gets.chomp
puts "enter flight number"
#number = gets.chomp
puts "enter flight origin location"
#origin = gets.chomp
puts "enter destination"
#destination = gets.chomp
end
def print_flight
puts "_____Flight details______"
puts "Flight_id : " + #id.to_s
puts "Flight_number : " + #number.to_s
puts "Flight_origin : " + #origin
puts "Flight_destination: " + #destination
end
def read_flights
puts "_______Array of flights______"
flightid = Array.new
flightid.push({ #id,#number,#origin,#destination })
puts "#{flightid}"
end
end
Check:
input_flight = Flight.new
input_flight.read_flight
input_flight.print_flight
input_flight.read_flights
So i create a new class and i have a lot of objects in this class such as name, surname age etc.
But i am geting the same error everytime. And also i do not now how to list my arrays with using method.
Error: no implicit conversion of Array into String
def main
patients = []
puts "What do you want to do \nadd \nlist \nexit"
process = gets.chomp
if process == "add"
puts "Please enter patient's name"
patient1 = Patient_Covid_19.new()
patient1.Name = gets.chomp.to_s
patient1.Name << patients #error line
elsif process == "list"
#And i want to print the arrays(patients, ages, surnames etc.) in here but using a method.
elsif process == "exit"
puts "Have a nice day"
else
puts "Please enter add, list or exit"
main
end
end
main
Edit: It was small syntax mistake(error line). But i still need help for the list process.
You probably meant to do patients << patient1.Name.
You can loop over and print out attributes as follows:
patients.each do |patient|
puts "Name: #{patient.Name}, etc"
end
class Patient_Covid_19
attr_accessor :Ssn, :Name, :Surname, :Sex, :Age
end
def main
patients = []
puts "What do you want to do \nadd \nlist \nexit"
process = gets.chomp
if process == "add"
puts "Please enter patient's name"
patient1 = Patient_Covid_19.new()
patient1.Name = gets.chomp.to_s
patients << patient1.Name
main
elsif process == "list"
elsif process == "exit"
puts "Have a nice day"
else
puts "Please enter add, list or exit"
main
end
end
main
This is my code. When the user writes Add, he will enter the patient's information from the console and this information will be added to an array. When the user writes list, he/she will be able to see the information of the patients he has written before. I want to do the listing with a method.
Why he gives me (Type error) in that statment
" address = cur.fetchone()[2] last = cur.fetchone()[4] no = cur.fetchone()[5] , while it accept "name = cur.fetchone()[1]" in the code : "
import sqlite3
conn = sqlite3.connect('myproject.sqlite')
cur = conn.cursor()
print "Welcome Mr/Hefnawy"
cur.execute('SELECT phone FROM participants')
b = cur.fetchone()[0]
while True:
a = raw_input("Enter Phone number here : ")
if a == b :
cur.execute('SELECT name,address,last_order,no_of_orders FROM participants WHERE phone = ?',(b, ))
name = cur.fetchone()[1]
address = cur.fetchone()[2]
last = cur.fetchone()[4]
no = cur.fetchone()[5]
print "The Costumer is already exist in Paricipants "
print "To edit the costumer data press (1)", "\n" , "to delet the costumer press (2)", "\n" , "add new order to the costumer press (3) "
c = raw_input("Enter your choice here : ")
if c == "1":
print "What do you want to edit ? , to edit name press 1 , to edit address press 2 , to edit phone press 3"
d = raw_input("Enter your choice here : ")
if d == "1" :
e = raw_input("New costumer name please ")
cur.execute('UPDATE participants SET name = ? WHERE phone = ?' , (e , a))
print "Costumer name has been updated to :", e
print ""
conn.commit()
else:
print "The costumer is not exist"
print b
print a , type(a)
When you are fetching something from a cursor say for example
t = cur.fetchone()
you can access the data from t using
print t[0],t[1],t[2] but In your case you are using multiple cur.fetchone() which allows you to use name = cur.fetchone()[1] that ends the data in the cursor. The second line address = cur.fetchone()[2] and the lines that follow it do not have a sql query executed for them to fetch, hence giving you the error. If you want to access the whole row just assign it to a variable and use the variable to get the data.
Im trying to learn how to add arrays into arrays, I have the following code:
puts "would you like to save a data set"
response = gets.chomp
if response == "y"
puts "create a new dataset?"
create_data_set = gets.chomp
while create_data_set == "y"
puts "what do you want to name the data set?"
dataset = gets.chomp
dataset = Array.new
puts 'would you like to add some grades to the array?'
store_grades_response = gets.chomp
while store_grades_response == "y"
puts 'enter grade ->'
grade = gets.chomp.to_i
dataset << grade
puts 'would you like to store another grade?'
store_grades_response = gets.chomp
end
all_data_sets = Array.new
all_data_sets.push(dataset)
puts "would you like to create a new data set?"
create_data_set = gets.chomp
end
end
puts all_data_sets
Im basically asking a user to enter a array name which should create an array, add values to the array and if required by the user add some more arrays and values to it. At last the array should be added to an array. And then I'm trying to display all the arrays.
The code works fine, I'm looping through everything but when it puts all_data_sets It only shows the last array that was created? i would like to store all the arrays within the one array called all_data_sets
The problem is that you are creating a new array all_data_sets at the end of each loop. One solution will be to have it before the loop.
puts "would you like to save a data set"
response = gets.chomp
all_data_sets = []
if response == "y"
puts "create a new dataset?"
create_data_set = gets.chomp
while create_data_set == "y"
puts "what do you want to name the data set?"
dataset = gets.chomp
dataset = Array.new
puts 'would you like to add some grades to the array?'
store_grades_response = gets.chomp
while store_grades_response == "y"
puts 'enter grade ->'
grade = gets.chomp.to_i
dataset << grade
puts 'would you like to store another grade?'
store_grades_response = gets.chomp
end
all_data_sets << dataset
puts "would you like to create a new data set?"
create_data_set = gets.chomp
end
end
puts all_data_sets
This way, you keep pushing the datasets into the all_data_sets after each loop.
I hope this is explanatory enough.
Fix
Its because your create new_data_sets array each time you do the loop, declare it outside enclosing while loop
Code
def main
mainDataSet = [] # All datasets
dataSetNames = [] # Incase you want to store data set names
response = getInput("Would you like to save a data set")
if(response == "y")
choice = getInput("Create a new dataset?")
while choice == "y"
dataset = getInput("What do you want to name the data set?")
dataSetNames << dataset
dataset = []
choice_2 = getInput("would you like to add some grades to the array?")
while choice_2== "y"
grade = getInput("Enter grade")
dataset << grade
choice_2 = getInput("Store another grade?")
end
mainDataSet << dataset
choice = getInput("Create a new data set?")
end
end
puts mainDataSet
puts dataSetNames
end
def getInput(message)
puts "#{message} -> "
gets.chomp
end
Hope this helps.
you can concat, prepend or append arrays just like this
dataset.concat all_dataset
dataset + all_dataset
Concat documentation
prepend or append
dataset.push(*all_dataset)
all_dataset.unshift(*dataset)
Array stuffs
Also you can do slice and whole bunch of stuffs check at the ruby docs link
So far I have this program doing what i want. However when running through it will overwrite the last employee record instead of just adding to the file. I'm new to prgramming and have been staring at this for hours and i can't get it yet. Just need a little nudge in the right direction.
# Define Employee Class
# Common Base Class for all Employees
class EmployeeClass:
def Employee(fullName, age, salary):
fullName = fullName
age = age
salary = salary
def displayEmployee():
print("\n")
print("Name: " + fullName)
print("Age: " + age)
print("Salary: " + salary)
print("\n")
EmployeeArray = []
Continue = True
print ("Employee Information V2.0")
while Continue == True:
print ("Welcome to Employee Information")
print ("1: Add New Record")
print ("2: List Records")
print ("3: Quit")
choice = input("Pick an option: ")
if choice == "1":
fullName = input ("Enter Full Name: ")
if fullName == "":
blankName = input ("Please enter a name or quit: ")
if blankName == "quit":
print ("Goodbye!")
print ("Hope to see you again.")
Continue = False
break
age = input ("Enter Age: ")
salary = input ("Enter Salary: ")
EmployeeRecords = open ('EmployeeRecords.txt' , 'w')
EmployeeRecords.write("Full Name: " + fullName + '\n')
EmployeeRecords.write("Age: " + age + '\n')
EmployeeRecords.write("Salary: " + salary + '\n')
EmployeeRecords.close()
elif choice == "2":
EmployeeRecords = open ('EmployeeRecords.txt', 'r')
data = EmployeeRecords.read()
print ("\n")
print (data)
EmployeeRecords.close
elif choice == "3":
answer = input ("Are you sure you want to quit? " "yes/no: ")
if answer == "yes" or "y":
print ("Bye!")
Continue = False
else:
Continue
else:
print ("Please choose a valid option")
print ("\n")
You are opening the file to be rewritten each time, based on the control string passed to open. Change open ('EmployeeRecords.txt, 'w')to open ('EmployeeRecords.txt', 'a+'). and the records will be appended to the end of the file.
Append mode should work.
EmployeeRecords = open('EmployeeRecords.txt', 'a')