0

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.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
Richard
  • 164
  • 7
  • What do you want to do in this line ` abil_check = $player[:abils][input.gsub("^a-z", "").to_sym]` ? – mrzasa Nov 12 '19 at 21:47
  • I want to define `abil_check` if `input` contains an ability score found in `$player[:abils]`. – Richard Nov 12 '19 at 21:50
  • 1
    OK, what exactly do you want to do using `gsub("^a-z", "")` ? – mrzasa Nov 12 '19 at 21:51
  • I want `abil_check` to only consist of the ability mentioned in `input`. (e.g.`-2 STR` should make `abil_check` equal `str`.) Then later I can do `$player[:abils][abil_check] + mod.to_i * (pos_or_neg ? 1 : -1)`. – Richard Nov 12 '19 at 21:56
  • So this gsub should filter out all non-letters, right? – mrzasa Nov 12 '19 at 22:00
  • Yes, that's what it should do. – Richard Nov 12 '19 at 22:01
  • It's difficult to tell you how to improve the code without a better idea how you'd use it. That also makes the question quite broad and subject to being off-topic. Please see "[ask]" and the linked pages and "[mcve](https://stackoverflow.com/help/minimal-reproducible-example)". – the Tin Man Nov 12 '19 at 23:06

1 Answers1

1

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"
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
mrzasa
  • 22,895
  • 11
  • 56
  • 94