Created
August 7, 2015 06:39
-
-
Save EdmundLeex/86754387a3154cdbc68c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# I/O Exercises | |
# | |
# * Write a `guessing_game` method. The computer should choose a number between | |
# 1 and 100. Prompt the user to `guess a number`. Each time through a play loop, | |
# get a guess from the user. Print the number guessed and whether it was `too | |
# high` or `too low`. Track the number of guesses the player takes. When the | |
# player guesses the number, print out what the number was and how many guesses | |
# the player needed. | |
# * Write a program that prompts the user for a file name, reads that file, | |
# shuffles the lines, and saves it to the file "{input_name}-shuffled.txt". You | |
# could create a random number using the Random class, or you could use the | |
# `shuffle` method in array. | |
def guessing_game | |
the_num = rand(1..100) | |
guess_count = 0 | |
print "Guess a number. " | |
input = nil | |
while input != the_num | |
guess_count += 1 | |
input = gets.to_i | |
if the_num < input | |
puts "Guess a number. #{input} is too high" | |
elsif the_num > input | |
puts "Guess a number. #{input} is too low" | |
else | |
puts "Bingo! The number is #{the_num}. You tried #{guess_count} times." | |
end | |
end | |
end | |
def shuffle_file | |
file_name = '' | |
until File.exists?(file_name) | |
puts "Please input a file name." | |
file_name = gets.chomp | |
end | |
all_lines = File.open(file_name).readlines | |
all_lines.shuffle! | |
f = File.new("#{file_name.sub('.txt', '')}--shuffled.txt", 'w') | |
all_lines.each { |line| f.puts line } | |
f.close | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment