Meinrad Recheis
3/4/2006 7:23:00 PM
On 3/4/06, Servando Garcia <garcia.servando@gmail.com> wrote:
>
> Hello all .
> I am a newbie to Ruby. I have been reading everything I can get my
> hands on about Ruby. I understand what a symbol is and how it saves
> memory space. I just can not seem to find any good reason to use one. I
> am sure I am missing something. Would some one please show me a good
> working example for using a symbol, please not the "Foo Bar" example
> again.
>
>
> Sam
>
hi Sam.
symbols are a coding style instrument:
personally, i use symbols whereever i want to refer to method names, as keys
in hashes or as other constant identifiers.
symbols as constant identifiers that need not be initialized are nicer than
code like this:
LAYOUT_CONSTANTS=[
LAYOUT_RIGHT=0,
LAYOUT_LEFT=1,
...
]
or even:
LAYOUT_CONSTANTS=[
LAYOUT_RIGHT="LAYOUT_RIGHT",
LAYOUT_LEFT="LAYOUT_LEFT",
...
]
code snippets that illustrate my coding style using symbols:
> if object.respond_to? :a_method
>
> { :key => "value" }
>
> subject.do_something( sideeffect=:notify)
you could use strings instead, but this kind of coding style enhances code
readability, because if you see a symbol you automatically associate it with
methods, variables, and constant expressions and the symbol syntax
differentiates these from normal (data-)strings.
i think i don't need to tell you guys why good coding styles are important
in software engineering :)
-- henon