带有两个参数的Ruby方法(一个具有默认值)只接受一个

Zit*_*one 2 ruby methods arguments

我想写一个PnP助手.我创建了一个包含统计数据和统计级别的哈希,并定义了一个方法来升级这些统计数据.这是我的哈希:

$stats = {
"HP" => 300,
"VIT" => 9,
"STR" => 10,
"DEX" => 15,
"SPD" => 8,
"INT" => 11,
"PSY" => 21,
"HW" => 2,
"MED" => 3,
"SCHW" => 0,
"GEN" => 12,
"RGEW" => 25,
"SELB" => 11,
"MKEN" => 19,
"WILL" => 23
}
Run Code Online (Sandbox Code Playgroud)

以下是我的方法:

def level_stat (stat, amount = 1)
  @string = stat.upcase
  print "#{@string}: #{$stats[@string]} > "
  $stats[@string] += 1 * amount
  puts $stats[@string]
  if (@string == "VIT")
    $stats["HP"] += 5 * amount
    print "#{"HP"}: #{$stats["HP"]} > "
    puts $stats["HP"]
  end
end
Run Code Online (Sandbox Code Playgroud)

amountstat的级别提升一级的默认值,但允许同时对同一个统计数据执行多个级别升级(或者它应该是这样).调用它按预期工作:

level_stat ("int")
Run Code Online (Sandbox Code Playgroud)

但是,调用以下语句会引发错误:

level_stat ("vit", 2)
# >> syntax error, unexpected ',', expecting ')'
#    level_stat ("vit", 2)
#                     ^
Run Code Online (Sandbox Code Playgroud)

我不明白为什么这样做.

Tom*_*ord 7

除去的空间之间level_stat(,或者完全去除括号:

level_stat("vit", 2)
level_stat "vit", 2
Run Code Online (Sandbox Code Playgroud)

通过添加空格括号,ruby解析器误解了你的意图并提出了一个SyntaxError.

如果您还没有,请快速浏览一下红宝石风格指南 - 通常的做法是省略以下空间def:

def level_stat(stat, amount = 1)
  # ...
end
Run Code Online (Sandbox Code Playgroud)

  • 另外:https://github.com/rubocop-hq/ruby-style-guide#parens-no-spaces (2认同)