问题描述
限时送ChatGPT账号..在带有散列的 ruby 中使用 =>
似乎很简单:
The use of =>
in ruby with hashes seems straightforward:
a = {key1: => value1, key2: => value2}
b = {"key1" => value1, "key2" => value2}
Ruby 使用了相当多的语法糖.这是一个示例代码块
Ruby makes quite a little bit of use of syntactic sugar. Here's an example code block
begin
[some code]
rescue Exception => e
[some error handling code]
end
救援线到底发生了什么,特别是在 Exception
和变量 e
之间以及 =>
之间?rescue
是保留关键字,e
显然是一个变量.其余的部分?在这种情况下=>
的作用是什么?
What exactly is going on in the rescue line, particularly between Exception
and the variable e
with the =>
in between? rescue
is a reserved keyword, e
is clearly a variable. The rest? What is the function of =>
in this case?
更新每个人似乎都没有抓住重点.我知道救援异常 => e"与哈希无关.我想从语法上知道该行中发生了什么.
Update Everyone appears to be missing the point. I know "rescue Exception => e" has nothing to do with hashes. I want to know syntactically what is going on in that line.
rescue"一词是关键字保留字,是 ruby 语言的一部分.我很确定e"是一个变量,在功能上也可以是a"、b"或c".什么是异常"和=>"?有没有另一种方式来写这个表达式,让像我这样的人更容易理解,他在编程时只学习语法严格且没有语法糖的语言?
The word "rescue" is a keyword reserved word and is part of the ruby language. I'm pretty sure "e" is a variable, and could just as functionally be "a", "b", or "c". What are "Exception" and "=>"? Is there another way to write this expression to make it more intelligible to a guy like me who cut his programming teeth on languages with rigid syntax and no syntactic sugar?
推荐答案
默认情况下,rescue
只救援 RuntimeError
,这也是 raise
的默认类,没有明确的异常类声明:
By default, rescue
only rescues RuntimeError
, which is also a default class for raise
without an explicit exception class declaration:
begin
raise "foo"
rescue
puts "rescued"
end
如果需要访问异常实例,可以使用以下语法:
If there is a need to get an access to the exception instance, one might use the following syntax:
begin
raise "foo"
rescue => e
puts "rescued #{e.message}"
end
也可以在不同的子句中拯救不同的异常:
One also might rescue different exceptions in different clauses:
class Error1 < RuntimeError; end
class Error2 < RuntimeError; end
begin
[some code]
rescue Error1 => e
puts "rescued an instance of Error1: #{e.message}"
rescue Error2 => e
puts "rescued an instance of Error2: #{e.message}"
rescue => e # standard RuntimeError
puts "rescued a generic error: #{e.message}"
end
也就是说,这种语法与哈希无关,它用于区分许多rescue
块中的不同异常类.
That said, this syntax has nothing to do with hashes and it’s used to distinguish between different exception classes in many rescue
blocks.
在您的示例中,有一个 Exception
(它不是 RuntimeError
的后继者,并且默认情况下未获救)已获救.虽然它被认为是一种不好的做法(因为这里的边距太小而无法描述),但有时它仍然有用.
In your example, there is an Exception
(which is not a successor of RuntimeError
and is not rescued by default) rescued. While it’s considered to be a bad practice (for the reasons margins here are too tiny to describe,) sometimes it’s still of some use.
这篇关于'=>' 的 Ruby 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论