Reputation: 164
I'm trying to write a character creator for an RPG, but there are two things I have questions about.
race_choice
is equal to any key within races
?player[race]
's value equal to the key/value pair for which race_choice
is equal to its key?Here's a simplified section of my code:
player = {
race: {}
}
races = {
human: {key1: "value", key2: "value"},
elf: {key1: "value", key2: "value"},
dwarf: {key1: "value", key2: "value"}
}
loop do
puts "What's your race?"
race_choice = gets.chomp.downcase
if race_choice == races[:race].to_s #I know this code doesn't work, but hopefully it
player[:race].store(races[:race, info]) #gives you a better idea of what I want to do.
puts "Your race is #{player[:race[:race]]}."
break
elsif race_choice.include?('random')
puts "Random race generation goes here!"
break
else
puts "Race not recognized!"
end
end
I want the player to select their race from a list of races, then add that race and its associated information to the player's character.
Upvotes: 1
Views: 312
Reputation: 23327
You can use the race_choice
string to access races
and then use the result:
race = races[race_choice.to_sym]
if race
player[:race] = race
elsif race_choice.include?('random')
#...
else
#...
end
You take the race_choice
, convert it to a symbol with to_sym
(because your races
hash is indexed with symbols). If the race is present in the hash, you assign it to player_race
, if not - you either randomize or handle error.
Upvotes: 1