Search code examples
regexrubystringif-statementruby-hash

Creating an RPG point buy system. Why is my if condition not being met?


I'm creating a point buy method for an RPG in which players modify their character's ability scores. My if condition is not being met when the input should be correct, and I can't tell why.

$player = {
  abils: {str: 10, con: 10, dex: 10, wis: 10, int: 10, cha: 10}
}


def abil_point_buy(x)
  points = x
  puts "<Add or subtract points from each ability (e.g. +2 STR, -1 CHA, etc.)>"
  loop do
    puts "<You have #{points} points remaining. Current ability scores:>"; print "<"
    $player[:abils].each { |abil, pts| print "#{abil.upcase}: #{pts} "}; puts ">"
    input = gets.chomp.downcase
    abil_check = $player[:abils][input.gsub("^a-z", "").to_sym]
    if abil_check && input.match?(/\d/) #checks if input contains a number and an ability score
      mod = input.gsub(/\D/, "") #determines amount to modify ability score by
      pos_or_neg = !input.include?('-') #determines if mod will be positive or negative
      $player[:abils][abil_check] + mod.to_i * (pos_or_neg ? 1 : -1) #adjusts selected ability score by mod
      pos_or_neg ? points - mod : points + mod
      break if points == 0
    else
      puts "Something is wrong with your input."
    end
  end
end

Would also appreciate general tips to improve my code.


Solution

  • You're using an invalid pattern in gsub. ^a-z is treated as "beginning of the line" followed by a dash and z. You need to replace it with a negated character class and downcase the string:

    "2 STR".downcase.gsub(/[^a-z]/, '')
    # => "str"