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

2

6

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
Metalloid answered 17/1, 2013 at 23:45 Comment(3)
Please work on indenting habits.Harriet
All of these examples come from: humblelittlerubybook.com/book/html/index.htmlMetalloid
You shouldn't do rescue Exception - Exception can include really severe errors. (Not criticising you, just the author of the tutorial).Ceylon
C
18

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.

Carolyn answered 18/1, 2013 at 0:54 Comment(1)
VERY good answer my friend - I switched to your answer here, though the other guy got me working faster. The reason I'm switching is for future people to understand that I believe this answer is more concise. Cheers,Metalloid
H
5

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}".

Harriet answered 17/1, 2013 at 23:46 Comment(8)
Thank you, and I found a great explination of what a hash literal is from: ruby-doc.org/docs/ProgrammingRuby/html/intro.htmlMetalloid
I'll accept your answer in about 5 minutes when StackOverflow lets me :)Metalloid
so in BAMBOO_HEAD = { 'life' => 120, 'hit' => 9 } - this is just making BAMBOO_HEAD = the string "{ 'life' => 120, 'hit' => 9 }"?Metalloid
@JeremyIglehart No, the assignment does not. puts ("put string") does. It calls #to_s on argument (a hash in this case) which results in the string. I updated that part of the answer which was misleading as puts does not return the argument.Harriet
So, what is going on with the DEATH = {'name' => value, 'another_name' => value2} - is this a hash literal? Is it creating an array and assigning it to DEATH? I'm confused. Forgive me, just trying to make sense of this Ruby stuff and the tutorial I'm reading is not as detailed as I'd like.Metalloid
It creates a Hash and assigns it to the constant DEATH. There is no Array in that line.Harriet
I found a good explanation to my previous comment/question here: ruby-doc.org/docs/ProgrammingRuby/html/intro.htmlMetalloid
See the link I added to the top of my answer. It should provide links to many useful resources! Happy coding.Harriet

© 2022 - 2024 — McMap. All rights reserved.