Ruby printing out hash data - arrays

I am working on a database that holds records for a school, where the key is the studentID, followed by the values of, first name, last name, major, and catalog year. I am working on the display function, which loops through the users which have been added to the hash. however, my code is not printing out of all the records i have added to the database.
it is only printing out one record listing, rather than my multiple inputted entries.
here is an example of input:
-----------------------------
Student Database Records
-----------------------------
1) Insert new record to database
2) Modify record in database
3) Remove record from database
4) Display record(s) in database
5) Quit
6) Enter choice:
1
-----------------------------
Add Record(s)
-----------------------------
Enter Student Identifcation Number:
32424
Enter First name of Student:
sfsdf
Enter Last name of Student:
sdfsfsf
Enter Major of Student:
sdfsdfs
Enter Catalogue Year:
sdfsfds
Your entry for Student ID 32424 has been added to the database.
------------------------------------------------------------------------
32424: sfsdf, sdfsfsf, sdfsdfs, sdfsfds
------------------------------------------------------------------------
here is my code to add an array to a hash
student_id = gets().chomp
if school_database.sDB.has_key?(student_id)
puts "Student Record Already Existent"
return school_database
end
puts "\nEnter First name of Student: "
first_name = gets().chomp
puts "\nEnter Last name of Student: "
last_name = gets().chomp
puts "\nEnter Major of Student: "
major = gets().chomp
puts "\nEnter Catalogue Year: "
catalogue_year = gets().chomp
puts "\nYour entry for Student ID #{student_id} has been added to the database.\n"
puts "\n------------------------------------------------------------------------"
puts "#{student_id}: #{first_name}, #{last_name}, #{major}, #{catalogue_year}"
puts "------------------------------------------------------------------------\n\n"
store_account_data = first_name + "," + last_name + "," + major + "," + catalogue_year
school_database.sDB[student_id] = [store_account_data]
return school_database
here is the code i am using to loop through my hash to print out the records.
school_database.sDB.each do |key, store_account_data|
puts "\n"
puts "#{key}: #{store_account_data.join(',')}"
positively, I run the .size command, and i discovered that it is adding muliple entries to the hash, however, it is not printing all of them
any ideas?

String’s + method places fairly strict requirements on what can appear on the right-hand side. You need to explicitly call to_s:
puts key + ' : ' + store_account_data.to_s
String interpolation is much more forgiving; it basically calls to_s for you:
puts "#{key} : #{store_account_data}"
Or perhaps you want a more detailed dump:
puts "#{key} : #{store_account_data.inspect}"
Or no brackets:
puts "#{key} : #{store_account_data.join(', ')}"
Or perhaps elements of store_account_data are objects, and you want to just print one property of them:
puts "#{key} : #{store_account_data.map(&:field_to_print).join(', '}"

I would do something like:
def display(database)
database.sDB.each do |key, account|
puts "#{key}: #{account.join(',')}"
end
end

You can use ruby's join method. I believe that's pretty common among languages.

Related

I am struggling to select a string of data from a database table and print it as a variable

I've been trying to learn how to use sqlite3 for python 3.10 and I can't find any explanation of how I'm supposed to grab saved data From a database and insert it into a variable.
I'm attempting to do that myself in this code but It just prints out
<sqlite3.Cursor object at 0x0000018E3C017AC0>
Anyone know the solution to this?
My code is below
import sqlite3
con = sqlite3.connect('main.db')
cur = con.cursor()
#Create a table called "Datatable" if it does not exist
cur.execute('''CREATE TABLE IF NOT EXISTS datatable
(Name PRIMARY KEY, age, pronouns) ''')
# The key "PRIMARY KEY" after Name disallow's information to be inserted
# Into the table twice in a row.
name = 'TestName'#input("What is your name? : ")
age = 'TestAge'#input("What is your age? : ")
def data_entry():
cur.execute("INSERT INTO datatable (name, age)")
con.commit
name = cur.execute('select name from datatable')
print(name)
Expected result from Print(name) : TestName
Actual result : <sqlite3.Cursor object at 0x00000256A58B7AC0>
The execute statement fills the cur object with data, but then you need to get the data out:
rows = cur.fetchall()
for row in rows:
print(row)
You can read more here: https://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/

How to split pascal case address in SnowFlake?

In order to create PlaceKey for addresses to link some of my tables, I need to split an address column in SnowFlake.
I am not familiar with JavaScript, but I tried Javascript UDF in SnowFlake. Then I don't know how to deal with the addresses like '123_45ThSt'.
The output of my function is like '123_45 Th St'. I am stuck here.
The expected output is '123 45Th St'.
Hope someone could help me out. Much appreciated!
Below is another example and my SnowFlake SQL code:
Original address column: 12345NE17ThSt
The expected column: 12345 NE 17Th St
My function's output: 12345 NE17 ST
My function:
CREATE OR REPLACE FUNCTION Split_On_Upper_Case(s string)
RETURNS string
LANGUAGE JAVASCRIPT
AS '
function Split_On_Upper_Case(str){
str=str.split(/(?=[A-Z])/).join(" ")
return str
}
// Now call the function
return Split_On_Upper_Case(S);
'
;
Assuming the format of street address, which includes number + word (ends with lower case or number) + word (start with upper case), I have below solution:
CREATE OR REPLACE FUNCTION Split_On_Upper_Case(s string)
RETURNS string
LANGUAGE JAVASCRIPT
AS $$
regexp = /([0-9]+)(NE|SE|NW|SW)?(.*[0-9a-z]{1})([A-Z][a-zA-Z0-9]+)/g;
splits = regexp.exec(S.replace(/_/g, " "));
if (splits && splits.length == 5) {
return
splits[1].trim() + " " +
(splits[2] ? splits[2].trim() + " ": "" ) +
splits[3].trim() + " " +
splits[4].trim();
}
return "not found" // or whatever you want to do
$$;
Then try to run the function:
select Split_On_Upper_Case('12345NE17ThSt');
-- 12345 NE 17Th St
select Split_On_Upper_Case('123_45ThSt');
-- 123 45Th St
select Split_On_Upper_Case('35TestSt');
-- 35 Test St
It returns expected output, but if you have more sample inputs, they can help to validate.

Reading data from SQLite3 database and using them

To start off, I really don't know if this have been answered before.
I looked all over but still couldn't find an example..
And I'm new to SQLite3 and obviously I would run into these kind of problems.
Basically what I'm doing is creating a SQLite3 database save as : "Data.dll".
And I've created a table and inserted some data in there..
Now, basically what I want to do is like ask the user a question, and the user has to input a number AND a "Key".
When inputted I want to check if it's valid.
For example,
DATA #1 :
NUMBERID : 30138
KEY: KeyUser1
DATA #2 :
NUMBERID : 1144
KEY : key2
If those were both inputted (Like 30138, and KeyUser1. not like 30138 and key2) then they can keep going, otherwise, It would say that the NUMBER ID and "KEY" Do not match.
So how can I do that?
I'm new to SQLite3 and so I'm still a newbie...
Any help is appreciated.
My Code:
import sqlite3
dbase = sqlite3.connect("Data.dll")
print "DataBase Opened : Success."
dbase.execute(""" CREATE TABLE IF NOT EXISTS Keys(
NUMBERID INT PRIMARY KEY NOT NULL,
VAILD TEXT NOT NULL)""")
print "DataBase Table : Success"
def insert_record(NUMBERID,VAILD):
dbase.execute(""" INSERT INTO Keys (NUMBERID,VAILD)
VALUES(?,?)""", (NUMBERID,VAILD))
dbase.commit()
#insert_record(1144, 'key2') # If needed to insert soemthing...
print "DataBase Insert : Success."
def read_Data():
data = dbase.execute(""" SELECT NUMBERID,VAILD FROM Keys """)
for record in data:
NUMBER_ID = str(record[0])
VAILD_KEY = str (record [1])
print NUMBER_ID # Check
print VAILD_KEY # Check
read_Data()
NUMBER_ENTER = input ("Enter NUMBER ID : ")
VAILD_ENTER = raw_input ("Enter KEY : ")
if NUMBER_ENTER in NUMBER_ID:
print "1" # If its at least correct print this
...
else:
print "2" # wrong
...
if VAILD_ENTER in VAILD_KEY:
print "a" # if its at least correct , print this.
...
else:
print "z" # wrong
...
dbase.close()
print "DataBase Closed : Success."
you could try this:
def check(number, key):
data = dbase.execute("select 1 from keys where NUMBERID = ? AND VAILD = ?", (number, key)).fetchone()
return data
NUMBER_ENTER = input("Enter NUMBER ID : ")
VAILD_ENTER = raw_input("Enter KEY : ")
if check(NUMBER_ENTER, VAILD_ENTER):
print 1
else:
print 2
where you check if there is a row with the NUMBERID, VAILD

How to use user input to create databases

How do I get input from user to create databases in python? These data must stored in test.db file.
Code
import sqlite3
conn = sqlite3.connect('test.db');
print "Opened database successfully";
name=raw_input ("enter your name: ");
salary=raw_input("enter your salary: ");
conn.execute("INSERT INTO employee (NAME,SALARY) \
VALUES ( r"+name+",r "+salary+")");
conn.commit()
Your concatenation is broken here, if salary is an integer you should do something like that:
conn.execute("INSERT INTO employee (NAME,SALARY) \
VALUES ( \"" + name + "\", " + str(salary) + ")");
Basically you need to escape some quotes around strings in your query.
Then to read your table you can do something like that:
for row in conn.execute('SELECT * FROM employee'):
print row

Trouble adding elements to a table (array in Lua)

I am attempting to create a table to serve as a small database for users:
users = {}
function create_new_user()
print("Enter a unique user name (up to 12 letters): ")
local name = io.read()
if #name > 12 then
print ("That name is too long.")
return create_new_user()
elseif users[name] then
print ("That name is already in use.")
return create_new_user()
else
table.insert(users, 1, name)
print("Your new user name is: ", users[name])
end
end
I understood from the manual that the line
table.insert(users, 1, name)
would insert the string value of name as an element of the users array. This is not the case-- whenever I run the script I get the following output:
Your new user name is: nil
You insert the element into the table, but you are trying to retrieve the value indexed by the value of name, which is not what you stored (you are using users[name] instead of users[1]). You can probably do something like this:
table.insert(users, name)
print("Your new user name is: ", name)
Note that table.insert(users, 1, name) may not do what you expect as this will prepend elements to the table. If you insert "abc" and "def" this way, then the users table will include elements {"def", "abc"} (in this particular order). To retrieve the last inserted element you can use users[1].
If you want to store values in a different order, you need to use table.insert(users, name), which will append elements to the table. To retrieve the last element you can use users[#users].
If you always want to store the added element in the first position in the table, then you can simply use users[1] = name.
Here you index the user table with a string (the name):
elseif users[name] then
You do the same here:
print("Your new user name is: ", users[name])
But you store the name with a numerical index:
table.insert(users, 1, name)
What you want instead of that line is:
users[name] = name
Or this (which would require changing the line that follows):
users[name] = true
The idea is you're only really using the keys, to create a lookup table.

Resources