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.

2
  • 1
    I'd recommend removing one of the two questions. They're not closely related resulting in a broad question. Please see "How to Ask" and the linked pages and "mcve". Commented Nov 10, 2019 at 5:35
  • Understood. Thanks for the edits and advice. Will try to improve my posts in the future. Commented Nov 10, 2019 at 13:36

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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]}."
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'},

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.