Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "=>" in "rescue Exception => e" do?

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
like image 435
Jeremy Iglehart Avatar asked Dec 01 '22 20:12

Jeremy Iglehart


1 Answers

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.

like image 129
Todd A. Jacobs Avatar answered Jan 08 '23 10:01

Todd A. Jacobs