San Diago
San Diago

Reputation: 1050

Saving data in a command-line game, no database [Ruby]

I'm making a simple command line game with Ruby and I'm having trouble saving some information without a database/HTTP dynamic.

For example, let's say I have to make a sandwich (in the game). I am presented with an array of ingredients to choose from, like so:

[1] Carrot
[2] Banana
[3] Cheese
[4] Tomato

I cannot hardcode a direct correspondence between number and ingredient because, before that, I was forbidden to use a couple of ingredients, at random (so the complete ingredients array is two items longer). And I don't want to present a list numbered like [1] [2] [4] [6] because it gets confusing.

What I'm doing right now is hardcoding a direct correspondence between a letter and an item, so for Banana press B, for Cheese press C and so on. But it's less than ideal, particularly because this is a pattern used throughout the game, and in some contexts it will get very inconvenient, both for me and the player.

So, is there a better way for me to do this? How can I associate an input with an item of a list that is generated randomly, and also save that information for further use down the line)?

Upvotes: 0

Views: 204

Answers (1)

San Diago
San Diago

Reputation: 1050

Here's how I solved it:

Mario Zannone's comment made me realize I could use the index of the array elements as an id, whereas I had been looking at the whole thing as if it was sort of just text.

So here's the code I came up with to take advantage of that:

([email protected]).each do |i|
    puts "[#{i+1}] #{@ingredients[i]}"
end

That way I now have a direct correspondence between element and input with:

choice = gets.chomp.to_i - 1
@selected_ingredient = @ingredients[choice]

Upvotes: 0

Related Questions