Last Updated
Viewed 33 Times
  

I'm working on a game in ruby, and I'm trying to make the computer save the player's score if they beat their high score. The high score file is a .txt file and is one line long.

high_score = File.read("rpsscore.txt")
if high_score.to_i < score
    File.open("rpsscore.txt", "w") { |f| f.write "#{score}" }
    print_slowly("Your high score is #{high_score}")
else
    print_slowly("Your high score is #{score}")
end 

When I run the code, I don't get any error message, but the file doesn't change, and stays at 0. I want the txt file to store the high score for the game.

Does anyone know how to do this?

(Don't worry about the print_slowly function, it's just a function that I made to make my text look fancy)

(score is the player's score after the game, which is represented by an integer.

So, I have a function that creates an object specifying user data. Then, using the Ruby YAML gem and some code, I put the object to a YAML file and save it. This saves the YAML file to the location where the Ruby script was run from. How can I tell it to save to a certain file directory? (A simplified version of) my code is this

print "Please tell me your name:  "
$name=gets.chomp
$name.capitalize!
print "Please type in a four-digit PIN number:  "
$pin=gets.chomp

I also have a function that enforces that the pin be a four-digit integer, but that is not important.

Then, I add this to an object

new_user=Hash.new (false)
new_user["name"]=$name
new_user["pin"]=$pin

and then add it to a YAML file and save it. If the YAML file doesn't exist, one is created. It creates it in the same file directory as the script is run in. Is there a way to change the save location? The script fo save the object to a YAML file is this.

def put_to_yaml (new_user)
File.write("#{new_user["name"]}.yaml", new_user.to_yaml)
end
put_to_yaml(new_user)

Ultimately, the question is this: How can I change the save location of the file? And when I load it again, how can i tell it where to get the file from?

Thanks for any help

I want to read from and write to the same EXCEL file (file.xls) using Ruby. I tried to use Roo gem which doesn't allow to write to the file. Now I am using Spreadsheet gem, but I can't update existing data in the same excel file.

Is it possible to read from and write to the same EXCEL file without change in macros using Ruby?

Similar Question 3 : How to write to file in Ruby?

I need to read the data out of database and then save it in a text file.

How can I do that in Ruby? Is there any file management system in Ruby?

Similar Question 4 (3 solutions) : ruby read and write/change the same file

Similar Question 5 (4 solutions) : Ruby read/write to file in 1 line of code

Similar Question 8 (2 solutions) : How to write a file with ruby? [duplicate]

Similar Question 9 (1 solutions) : how to organize read\write to lsb in ruby

cc