Search code examples
rubystringruby-hash

How to check if a string is equal to any key within a hash and editing another hash based on the result


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.


Solution

  • 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.