1

I'm trying to write a character creator for an RPG, but there are two things I have questions about.

  1. How can I check if a string is equal to any key within a hash, in this case, if race_choice is equal to any key within races?
  2. How can I change another key's value in a different hash to equal the key/value pair which contains the key equal to my string, in this case, how to make 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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Richard
  • 164
  • 7
  • 1
    I'd recommend removing one of the two questions. They're not closely related resulting in a broad question. Please see "[ask]" and the linked pages and "[mcve](https://stackoverflow.com/help/minimal-reproducible-example)". – the Tin Man Nov 10 '19 at 05:35
  • Understood. Thanks for the edits and advice. Will try to improve my posts in the future. – Richard Nov 10 '19 at 13:36

1 Answers1

1

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.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • Thanks so much. This is way simpler than what I was trying to do. Another question: how can I print only the key of `player[:race]`? I want to interpolate it like this: `"Your race is #{player[:race]}."` – Richard Nov 09 '19 at 22:29
  • 1
    You need to store it separately - either as a separate variable, or as a separate key in `player` hash (e.g. `player[:race_name]`) or inside the race data `human: {key1: "value", key2: "value", name: 'human'},` – mrzasa Nov 09 '19 at 22:32