"中的 "rescue Exception => e"有什么作用?-6ren"> "中的 "rescue Exception => e"有什么作用?-举个例子: def method_of_doom my_string = "I sense impending doom." my_string.ah_ha_i_called_a_nonexisten-6ren">
gpt4 book ai didi

ruby - "=>"中的 "rescue Exception => e"有什么作用?

转载 作者:数据小太阳 更新时间:2023-10-29 07:41:21 24 4
gpt4 key购买 nike

举个例子:

def method_of_doom
my_string = "I sense impending doom."
my_string.ah_ha_i_called_a_nonexistent_method
rescue NoMethodError => e:
puts "PROBLEM: " + e.to_s
rescue Exception:
puts "Uhh...there's a problem with that there method."
end

在它说的那一行:

rescue NoMethodError => e:

'=>' 在做什么?

它与这种用法有何不同:

module FighterValues
BAMBOO_HEAD = { 'life' => 120, 'hit' => 9 }
DEATH = { 'life' => 90, 'hit' => 13 }
KOALA = { 'life' => 100, 'hit' => 10 }
CHUCK_NORRIS = { 'life' => 60000, 'hit' => 99999999 }

def chuck_fact
puts "Chuck Norris' tears can cure cancer..."
puts "Too bad he never cries."
end
end

module ConstantValues
DEATH = -5 # Pandas can live PAST DEATH.
EASY_HANDICAP = 10
MEDIUM_HANDICAP = 25
HARD_HANDICAP = 50
end

puts FighterValues::DEATH
→ {'life'=>90,'hit'=>13}

puts ConstantValues::DEATH
→ -5

最佳答案

Hash Rocket 是一种句法 token

哈希火箭实际上是一个句法标记。您可以在 ext/ripper/ripper.y 定义的语法中找到 token :

%token tASSOC           /* => */

换句话说,Ripper 使用哈希火箭关联事物。

如何使用 tASSOC

通常,此标记用于散列文字中以将键与值相关联。例如:

{ :e => 'foo' }

将字符串文字 foo 与符号 :e 相关联。这种常见用法就是为什么人们倾向于将哈希火箭仅视为与哈希相关的结构。

另一方面,以下将变量与异常相关联:

rescue => e

在这种情况下,Ripper 不是将键与值相关联,而是将变量 e 与隐含的 StandardError 异常相关联,并使用该变量存储值的 Exception#message .

进一步阅读

如果您了解分词器、词法分析器和解析器,ripper.yext/ripper/lib/ripper 的各种内容都具有指导意义。然而,在 Ruby Under a Microscope 的第 19 页,Pat Shaughnessy 警告说:

Ruby doesn’t use the Lex tokenization tool, which C programmers commonly use in conjunction with a parser generator like Yacc or Bison. Instead, the Ruby core wrote the Ruby tokenization code by hand.

当您尝试在源代码级别理解 Ruby 的语法时,请牢记这一点。

关于ruby - "=>"中的 "rescue Exception => e"有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14390182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com