我是 Ruby 新手,并试图了解它的一些语法。
为什么此代码与异常对象的变量一起使用:
begin
puts Dir::delete
rescue ArgumentError => e
puts e.backtrace
end
但不带符号?
begin
puts Dir::delete
rescue ArgumentError => :e
puts e.backtrace
end
我是 Ruby 新手,并试图了解它的一些语法。
为什么此代码与异常对象的变量一起使用:
begin
puts Dir::delete
rescue ArgumentError => e
puts e.backtrace
end
但不带符号?
begin
puts Dir::delete
rescue ArgumentError => :e
puts e.backtrace
end
Symbol is a value. In your example you need a variable to store the Error object. You usually use symbols as string constants.
For example, if you create a module with cardinal directions it is better to use the symbols :north, :south, :east, :west rather than the strings "north", "south", "east" and "west".
Symbols are often used as keys in hashes:
my_hash = { a: 1, b: 7, e: 115 }
It's very useful to read ruby code on github for instance in order to understand when to use symbols.
因为,正如您在问题本身中所写,您需要一个 Exception 对象,而不是 Symbol 对象。
在救援块中,您backtrace通过e对象访问,该对象是 type ArgumentException,而不是 type Symbol。
因此,解释器解析时实际发生的:e是,间接Symbol创建了一个新对象并将其值设置为:e. 这就像 write 23,其中Fixnum间接创建了一个对象并将其值设置为 23。
但是符号本身可以存储在变量中:
some_var = :e
e = :e
希望我的意思很清楚。
我认为这e是一个存储异常对象的变量,并且:e是一种数据类型,因此它是一种值。
一些例子
# standard way of assign variable will work
e = ArgumentError.new
# assign to data will not work
:e = ArgumentError.new
'e' = ArgumentError.new
1 = ArgumentError.new
符号代替变量名 - 从不(符号是一个值,名称是一个名称。苹果和橙色);
变量代替符号 - 如您所愿(如s = :name; puts params[s]);
用符号代替字符串——小心(如果你创建了太多的符号,你可能会遇到麻烦)。