From: Paul Harrington Date: 2010-02-08T01:56:28+09:00 Subject: Re: Symbols and class veriable Jerome David Sallinger wrote: > Hello, Is the any connection between a symbol and a class variable. For > example, if I declare the variable @red_car_speed is this aliased or > connected by :red_car_speed. The section of code that is confuring me > is: > > ------------------------------------------------------- > require 'ruby-processing' > > class TwoCarObjects < Processing::App > load_library :control_panel > > def setup > control_panel do |c| > c.slider :red_car_speed, -5..15 > c.slider :blue_car_speed, -5..15 > end > > # Initialize car objects > @red_car = Car.new(self, color(255,0,0), 0, 100) > @blue_car = Car.new(self, color(0,0,255), 0, 10) > @red_car_speed = 1 > @blue_car_speed = 2 > rect_mode CENTER > end > > def draw > background 255 > > # Operate the car object in draw > # by calling object methods using the dots syntax. > @red_car.move(@red_car_speed) > @red_car.display_car > @blue_car.move(@blue_car_speed) > @blue_car.display_car > end > > end > ------------------------------------------------------- > > It seems that the symbols and class variable for, for example > red_car_speed are linked @variable_name is an *instance* variable, not class variable. They are scoped to the individual instances of a class, whereas class variables can be thought of as "globals" accessible to all instances of a particular class (the behavior of class variables in Ruby is strange and inconsistent between versions, so avoid using them). Symbols are actually fairly similar to strings, except with stricter rules about their contents, are immutable, act like singletons (each symbol representation only is created once, so if a = :test; b = :test, then a.object_id == b.object_id), and are never garbage collected. For the last the reasons symbols are often treated as identifiers in Ruby; many methods use symbols to look up or return the the names of variables or methods. They're also commonly used as hash keys, or really just about any situation that requires a accessing something by name, the name probably lasting the life of the Ruby process. However, symbols really have no intrinsic relation to any sort of variable; this illusion rises strictly from convention. -- Posted via http://www.ruby-forum.com/.