Roman
Roman

Reputation: 10403

When is it correct to use symbols in place of variables in Ruby?

I'm new to Ruby and trying to get my head around some of its syntax.

Why does this code work with a variable for the exception object:

begin
  puts Dir::delete
rescue ArgumentError => e
  puts e.backtrace
end

but not with a symbol?

begin
  puts Dir::delete
rescue ArgumentError => :e
  puts e.backtrace
end

Upvotes: 2

Views: 113

Answers (4)

Sergey
Sergey

Reputation: 11908

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.

Upvotes: 3

Suborx
Suborx

Reputation: 3669

I think the e is a variable where is stored the exception object and :e is a data type so it is kind of value.

some examples

# 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

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

Symbols in place of variable names - never (symbol is a value, name is a name. Apple and orange);

Variables in place of symbols - as you wish (as in s = :name; puts params[s]);

Symbols in place of strings - with care (if you create too many symbols, you might run into troubles).

Upvotes: 1

Vapire
Vapire

Reputation: 4578

Because, as you write in the question itself, you need an Exception object, not a Symbol object.

In the rescue block you're accessing backtrace via the e object, which is of type ArgumentException, not of the type Symbol.

So what actually happens when the interpreter parses :e is, that indirectly a new Symbol object is created and its value is set to :e. It's like writing 23, where a Fixnum object is indirectly created and its value is set to 23.

But a symbol itself can be stored in a variable:

some_var = :e
e = :e

Hope it's clear what I mean.

Upvotes: 2

Related Questions