Alle marted? 14 agosto 2007, maghac ha scritto:
> Hi,
> as a long-term perl user just recently converted to ruby, I'm curious
> about one particular syntax "feature": ruby symbols and how they
> relate to strings.
>
> Isn't really :name a shortcut for "name"? (I read somewhere in an
> explanation of attr_reader that e.g :age was the "name" of the
> variable age, while age is the actual content of that variable). If
> so, couldn't you use this in hash keys as well, e.g say hashvar[:key]
> instead of hashvar['key'].
>
> Are there situations where you cannot use symbols instead of strings,
> or the other way around?
>
> I might be too used to the way strings and barewords are handled in
> perl (if something looks like a string, and it's not a function call,
> it's interpreted as a string. This means you can say $hashvar{key}
> without quoting the key).

Symbols and strings are two different things. There are several situations in 
which you can pass a method either a symbol or a string, but this happens 
because who wrote the method took into account both possibilities. For 
instance, attr_reader and similar, send, instance_variable_get and 
instance_variable_set, define_method can take both a string or a symbol. 
Module#const_get, instead, only accepts a symbol.

You can see that string and symbols are different using hashes:

h = { :a => 1}
puts h[:a]
=> 1
puts h['a']
=> nil
h['a'] = 2
puts h['a']
=> 2
puts h[:a]
=> 1

There have been several threads on this topic. I suggest you look at them.

I hope this helps

Stefano