问题
Given the example:
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
On the line where it says:
rescue NoMethodError => e:
What is the '=>' doing?
How is it different than this usage:
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
回答1:
The Hash Rocket is a Syntactic Token
The hash rocket is actually a syntactic token. You can find the token in the grammar defined by ext/ripper/ripper.y
:
%token tASSOC /* => */
In other words, Ripper uses the hash rocket to associate things.
How tASSOC is Used
In general, this token is used in hash literals to associate a key with a value. For example:
{ :e => 'foo' }
associates the string literal foo
with the symbol :e
. This common usage is why people tend to think of the hash rocket as solely a hash-related construct.
On the other hand, the following associates a variable with an exception:
rescue => e
In this case, rather than associating a key with a value, Ripper is associating the variable e
with the implied StandardError
exception, and uses the variable to store the value of Exception#message.
Further Reading
If you understand tokenizers, lexers, and parsers, ripper.y
and the various contents of ext/ripper/lib/ripper
are instructive. However, on page 19 of Ruby Under a Microscope, Pat Shaughnessy warns:
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.
Just something to keep in mind when you're trying to grok Ruby's grammar at the source code level.
回答2:
There are a bunch of good links on the Ruby Info page.
It depends on context.
In the context of a rescue
it means:
"Assign the exception object to the variable e
."
This is how it can be used as e.to_s
later.
In a Hash literal it means:
A pair, represented by key=>value.
Here is a Hash literal is created from two pairs: {:name => "Fred", :age => 20}
(Ruby 1.9/2.0+ also allows {name: "Fred", age: 20}
syntax, where name
and age
refer to Symbols.)
In a String, it is what it is:
"=>Whee!".
In this case puts FighterValues::DEATH
, is equivalent to puts FighterValues::DEATH.to_s
. That is, the output displayed comes from a string. Consider this: puts "{a => b}"
.
来源:https://stackoverflow.com/questions/14390182/what-does-the-in-rescue-exception-e-do