为 D&D 制作骰子滚筒;为什么 Ruby 给我一个 NameError?

Making a dice roller for D&D; why is Ruby giving me a NameError?

我对编码很陌生,一直在努力改进我发现的用于 D&D 的骰子滚筒 here。我有一个变量可以确定 roll 的修饰符是正数还是负数,但由于某种原因 Ruby 给我一个 NameError(未定义的局部变量或方法 `pos_or_neg' for main:Object)。也将感谢使我的代码更好的一般建议。

def roll(amount = 0, sides = 0)
  #For every die(amount), randomly generate a result limited to sides, then add all results together.
  amount.to_i.times.sum { |t| rand(1..sides.to_i) }
end

puts "Gimme some dice to roll! (e.g. 2d4, 1d12-1, etc.)"
loop do
  input = gets.chomp.to_s

  abort("May your rolls be ever natural.") if input == "exit"
  next puts "Please specify the number of dice!" if input.start_with?("d")

  #Check if modifier is positive or negative.
  pos_or_neg == true if input.include? "+"; pos_or_neg == false if input.include? "-"

  #Replace everything but numbers with spaces in input, then split.
  amount, sides, mod = input.tr("^0-9", " ").split

  #Calculate final result using pos_or_neg to determine modifier.
  pos_or_neg == true ? fin = roll(amount, sides) + mod.to_i : roll(amount, sides) - mod.to_i
  puts fin

end

如果这种事情经常被问到,我深表歉意。

Yurii 在对你的问题的评论中所说的,你是在比较 (==) 而不是赋值 (=)。

而且,如果 input 中既没有“+”也没有“-”,那么 pos_or_neg 将不会被定义。您可以更改行:

 pos_or_neg == true if input.include? "+"; pos_or_neg == false if input.include? "-"

与:

 pos_or_neg = !input.include?('-')

(假设既没有'+'也没有'-'的情况为正)

并且(我认为)如果您更改此行,它会更具可读性:

pos_or_neg == true ? fin = roll(amount, sides) + mod.to_i : roll(amount, sides) - mod.to_i

  fin = roll(amount, sides) + mod.to_i * (pos_or_neg ? 1 : -1)