How do I get the elsif for #correct_tries to work properly? - arrays

My first hangman game from scratch is almost done with the real basic stuff. I just need a counter for when a player gets it right to work correctly. I haven't figured out a good way to do it without deleting everything and starting over.
the #correct_tries counts correctly then in the elsif compare the numerical value to the number of elements in the given word that were answered correctly.
It'll keep counting when it should have stopped when #correct_tries was compared to the number when .inspect happens on the array. But it keeps counting.
class Hangman
Profanity = ['cobol','snit','crap','court']
Adjective = ['foul','repugnant','swift','fast']
Noun = ['king','queen','prince','princess']
def self.start_game
print "Welcome to Hangman V1 by Clueless! Please select which category of words do you want to use: \n Profanity, Adjective, Noun "
#selection = gets.chomp.downcase
case
when #selection == 'profanity'
puts 'You have selected profanity! '
hangman_word_selection
when #selection == 'adjective'
puts 'You have selected Adjectives! '
hangman_word_selection
when #selection == 'noun'
puts 'You have selected nouns! '
hangman_word_selection
end
end
def self.hangman_word_selection
if #selection == 'profanity'
hangman_word = Profanity.sample
hangman_word_setup(hangman_word)
#puts '_ ' * hangman_word.size
elsif #selection == 'adjective'
hangman_word = Adjective.sample
hangman_word_setup(hangman_word)
elsif
#selection == 'noun'
hangman_word = Noun.sample
hangman_word_setup(hangman_word)
end
end
def self.hangman_word_setup(hangman_word)
hangman_word_array = hangman_word.chars.to_a
#hangman_end = false
#while(#hangman_end == false)
#puts "*" * 40
#puts
#puts
puts 'You have five tries to get the word correct. If you can guess the whole word do so but you only have one try. Or just guess letter by letter.'
p hangman_word_array
#total_tries = 0
#correct_tries = 0
game_check = true
while game_check == true
first_try = gets.chomp.downcase
if(first_try == hangman_word_array[0] || first_try == hangman_word_array[1] || first_try == hangman_word_array[2] || first_try == hangman_word_array[3] || first_try == hangman_word_array[4])
puts 'Check'
#correct_tries += 1
p #correct_tries
#correct tries equal to the number of chars in the given word check it.
puts 'You have gotten it correct!'
elsif(first_try == hangman_word)
puts 'You have completed the word! Congratulations you win!'
hangman_win
break
elsif(first_try != hangman_word_array)
puts 'Wrong.'
#total_tries += 1
p #total_tries
#puts "*" * 40
elsif(#correct_tries == hangman_word_array.inspect)
puts 'done.'
break
end
end
end
def self.hangman_loss
puts ' +---+-
| |
| 0
| |\\
| /\\
-+----------'
puts 'You lose!'
end
def self.hangman_win
puts 'NEED HANGMAN VICTORY POSE HERE.'
end
start_game
end

The elsif condition
elsif(#correct_tries == hangman_word_array.inspect) will never be true. #correct_tries is a numerical value and hangman_word_array.inspect will return the array of words for hangman in a string format (e.g. hangman_word_array = ['a', 'b', 'c'] then hangman_word_array.inspect will be "[\"a\", \"b\", \"c\"]".

Related

How to solve Ruby Wizardry "Staying in the loop" example program?

The book Ruby Wizardry Chapter 4 includes the following sample program
we_wanna_ride = true
stops = ["East Bumpspark", "Endertromb Avenue", "New Mixico", "Mal Abochny"]
while we_wanna_ride
print "Where ya headin', friend?"
destination = gets.chomp
if stops.include? destination
puts "I know how to get to #{destination}! Here's the station list:"
stops.each do |stop|
puts stop
break if stop == destination
end
else
puts "Sorry, we don't stop at that station. Maybe another time!"
we_wanna_ride = false
end
end
It then goes on to pose a few additional challenges:
"What if a passenger is going the other way on the train (for instance, from Mal Abochny to East Bumpspark)? How could you update your program to work in both directions? Even trickier, what if the train route is a big circle (meaning if a passenger goes from East Bumpspark to Mal Abochny, the next stop after Mal Abochny should be East Bumpspark again)? How could you update your program to print out the right list of train stops if a passenger wants to go all the way around the circle?"
Does anybody have any ideas how to proceed here ? I'm a beginning programmer so any help would be greatly appreciated. Here's my progress so far. I figured I would get a departure from the user and then use to.i to get the input into an integer. I could then use the integer value to compare to the index position in the array. If the rider wants to go in the opposite direction I could use something like stops.each.reverse to print out the array items in reverse order.
we_wanna_ride = true
stops = ["East Bumpspark(1)", "Endertromb Avenue(2)", "New Mixico(3)", "Mal Abochny(4)"]
puts "#{stops}"
while we_wanna_ride
print "Select a destination number"
destination = gets.chomp.to_i
print "Select a departure number"
departure = gets.chomp.to_i
if departure <= destination
stops.each do |stop|
puts stop
break if stop == destination
end
else puts "Sorry"
we_wanna_ride = false
end
end
Here is how I solved this challenge. It works but is rather lengthy. More advanced ruby coders may be able to provide a shorter solution:
we_wanna_ride = true
stops = ["East Bumpspark", "Endertromb Avenue", "New Mixico", "Mal Abochny"]
while we_wanna_ride
print "Where do you wish to depart from?: "
depart = gets.chomp.split.map(&:capitalize).join(' ')
depart_index = stops.index(depart)
# puts depart_index
print "Where ya headin' friend?: "
destination = gets.chomp.split.map(&:capitalize).join(' ')
destination_index = stops.index(destination)
# puts destination_index
index_diff1 = depart_index - destination_index
index_diff2 = destination_index - depart_index
if stops.include? destination && depart
puts "\nI know how to get to #{destination}! Here's the station list:"
if destination_index > depart_index && index_diff2 < 3
stops[depart_index..-1].each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index > depart_index && index_diff2 >= 3
dubstops = stops.concat(stops)
dubstops[0..depart_index+4].reverse_each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index < depart_index && index_diff1 < 3
stops[0..depart_index].reverse_each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
elsif destination_index < depart_index && index_diff1 >= 3
dubstops = stops.concat(stops)
dubstops[depart_index..-1].each do |stop|
puts stop
break if stop == destination
end
we_wanna_ride = false
end
else
puts "Sorry, we don't service that station. Maybe another time!"
we_wanna_ride = false
end
end

Ruby, how can i compare a string with a specific element of array?

I create an array from a text file which contains the english irregular verbs. I want the code to ask me the verbs in random order letting me proceed only if I respond correctly. I need to compare a string with an element of array. I wrote this:
a = []
File.open('documents/programmi_test/verbi.txt') do |f|
f.lines.each do |line|
a <<line.split.map(&:to_s)
end
end
puts ''
b = rand(3)
puts a[b][0]
puts 'infinitive'
infinitive = gets.chomp
if infinitive = a[b][1] #--> write like this, I receive alway "true"
puts 'simple past'
else
puts 'retry'
end
pastsimple = gets.chomp
if pastsimple == a[b][2] #--> write like this, I receive alway "false"
puts 'past participle'
else
puts 'retry'
end
pastpart = gets.chomp
if pastpart == a[b][3]
puts 'compliments'
else
puts 'oh, no'
end
can somebody help me?
if infinitive = a[b][1] is assigning to inifinitive the value of a[b][1], unlike pastsimple == a[b][2] that's a comparation between both values.
You could try replacing the = for ==.
a = []
File.open('documents/programmi_test/verbi.txt') do |file|
file.lines.each do |line|
a << line.split.map(&:to_s)
end
end
puts ''
b = rand(3)
puts a[b][0]
puts 'infinitive'
infinitive = gets.chomp
puts infinitive == a[b][1] ? 'simple past' : 'retry'
pastsimple = gets.chomp
puts pastsimple == a[b][2] ? 'past participle' : 'retry'
pastpart = gets.chomp
puts pastpart == a[b][3] ? 'compliments' : 'oh, no'

Adding an Array to an Array Ruby

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

Reading and writing files

I am trying to read one text file and convert the contents of that file to pig latin on a new file. Here is what I have:
def pl_line(word):
statement = input('enter a string: ')
words = statement.split()
for word in words:
if len(word) <= 1:
print(word + 'ay')
else:
print(word[1:] + word[0] + 'ay')
def pl_file(old_file, new_file):
old_file = input('enter the file you want to read from: ')
new_file = input('enter the file you would like to write to: ')
write_to = open(new_file, 'w')
read_from = open(old_file, 'r')
lines = read_from.readlines()
for line in lines():
line = pl_line(line.strip('\n'))
write_to.write(line + '\n')
read_from.close()
write_to.close()
However, when I run this, I get this error message:
TypeError: 'list' object is not callable
Any ideas of how to improve my code?
Here are some improvements to the actual converter:
_VOWELS = 'aeiou'
_VOWELS_Y = _VOWELS + 'y'
_SILENT_H_WORDS = "hour honest honor heir herb".split()
def igpay_atinlay(word:str, with_vowel:str='yay'):
is_title = False
if word.title() == word:
is_title = True
word = word.lower()
# Default case, strangely, is 'in-yay'
result = word + with_vowel
if not word[0] in _VOWELS and not word in _SILENT_H_WORDS:
for pos in range(1, len(word)):
if word[pos] in _VOWELS:
result = word[pos:] + word[0:pos] + 'ay'
break
if is_title:
result = result.title()
return result
def line_to_pl(line:str, with_vowel:str='yay'):
new_line = ''
start = None
for pos in range(0, len(line)):
if line[pos].isalpha() or line[pos] == "'" or line[pos] == "-":
if start is None:
start = pos
else:
if start is not None:
new_line += igpay_atinlay(line[start:pos], with_vowel=with_vowel)
start = None
new_line += line[pos]
if start is not None:
new_line += igpay_atinlay(line[start:pos], with_vowel=with_vowel)
start = None
return new_line
tests = """
Now is the time for all good men to come to the aid of their party!
Onward, Christian soldiers!
A horse! My kingdom for a horse!
Ng!
Run away!
This is it.
Help, I need somebody.
Oh, my!
Dr. Livingston, I presume?
"""
for t in tests.split("\n"):
if t:
print(t)
print(line_to_pl(t))
You very likely mixed up the assignments to read_fromand write_to, so you're unintentionally trying to read from a file opened only for write access.

Text file over written and not appended

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')

Resources