制作用于D&D的骰子辊; Ruby为什么给我一个NameError?

时间:2019-11-05 13:20:02

标签: ruby nameerror

我对编码非常陌生,一直在尝试改进here的D&D骰子滚子。我有一个变量,确定纸卷的修饰符是正数还是负数,但是由于某种原因,Ruby给了我一个NameError(未定义的局部变量或main:Object的方法“ pos_or_neg”)。也将感谢您提供有关改进我的代码的一般建议。

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

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

1 个答案:

答案 0 :(得分:1)

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)
相关问题