Hi Shannon,
pigeon% ruby -e ‘p :PropFind’
:PropFind
pigeon%
pigeon% ruby -e ‘p PropFind’
-e:1: uninitialized constant PropFind (NameError)
pigeon%
This only show the difference between symbol and name. But my key problem is
WHY we need symbol. What is it used FOR?
I don’t know how authoritative an answer I can present here, but:
I think symbols are neat. Whenever you type a specific symbol
in your program, say, :some_symbol, you get back a single corresponding
instance of class Symbol. Take a look at the object id’s in the
following example:
:some_symbol.id
3309838
:some_symbol.id
3309838
“some_string”.id
22399992
“some_string”.id
22394712
“some_symbol”.intern
:some_symbol
“some_symbol”.intern.id
3309838
Hopefully the above illustrates clearly enough that when creating a
Symbol, there is a one-to-one mapping between the name of the symbol,
and the instance of class Symbol existing in Ruby to represent a
symbol of that name. . . . .
As far as what they’re used FOR, I’ve only arrived at that through
induction. A typical use of symbols in Ruby is to represent the
name of a method. For ex: “string”.respond_to? :intern #=> true.
Or, as you’ve noted, method-defining methods such as attr_reader,
etc… It’s convenient notation to represent the name of the method
with a symbol… You could make a method like attr_reader that
worked with strings as arguments instead of symbols, if you wanted
to… but attr_reader “myvar” just doesn’t look as nifty to me as
attr_reader :myvar… (I suspect, also, that the
representation of method names as symbols is connected to the
mechanism of method-name lookup internally in Ruby classes, but I
have not perused that part of the Ruby source to verify this…)
In my own code, for what it’s worth, I tend to use symbols in
places where I might have in other languages used an integer
constant to represent a (certain kind of) recurring named type-
value. Such as:
NOUN = 0
VERB = 1
ADVERB = 2
ADJECTIVE = 3
Instead, in Ruby, I’ll just go: if word.type == :noun …
Hope this helps,
:bill #
···
From: “Shannon Fang” xrfang@hotmail.com