Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #2963

Re: Understanding global variables.

From 7stud -- <bbxx789_05ss@yahoo.com>
Newsgroups comp.lang.ruby
Subject Re: Understanding global variables.
Date 2011-04-15 13:10 -0500
Organization Service de news de lacave.net
Message-ID <a85b7b3997f94907d681ca2b1815a850@ruby-forum.com> (permalink)
References <962f80bb11f2292d2ba5498cbfca785c@ruby-forum.com> <2d350d202910142ee0f58ef60b4317c9@ruby-forum.com>

Show all headers | View raw


Fily Salas wrote in post #992993:
>
> This may be confusing because I have never heard about “SELF” statement,
> “INITIALZE” method and the “:” notation, I guess I need to read more
> about the language.
>

Knowing which object is 'self' is sort of an intermediate topic, but it 
is critical to understanding how ruby works.

> What would happen if I position a variable using the wrong syntax? In
> other words if I position a variable where an instance variable would
> normally go but without the @ will Ruby get confused and treat this
> differently and may get an error or the interpreter will simply use it
> and keep track of what kind of variable it is by itself.
>

A variable name that is not preceded by an '@', is called a 'local 
variable', and a local variable ceases to exist once the method ends. 
Here is an example:

class Dog
  def initialize(a_name, a_color)
    @name = a_name
    color = a_color
  end

  def name
    @name   #same as 'return @name'
  end

  def name=(str)
    @name = str
  end

  def color
    @color  #same as 'return @color'
  end


end

my_dog = Dog.new('Spot', 'black')
#Calling new() automatically causes initialize()
#to execute.

puts my_dog.name   #=> Spot
my_dog.name = 'Max'
puts my_dog.name   #=> Max

puts my_dog.color  #=> <nothing>


> Any good tutorial about variables in Ruby?

"Beginning Ruby (2nd ed)" by Cooper

-- 
Posted via http://www.ruby-forum.com/.

Back to comp.lang.ruby | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Understanding global variables. Fily Salas <fs_tigre@hotmail.com> - 2011-04-14 19:55 -0500
  Re: Understanding global variables. 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-14 20:05 -0500
  Re: Understanding global variables. jake kaiden <jakekaiden@yahoo.com> - 2011-04-14 22:30 -0500
  Re: Understanding global variables. Fily Salas <fs_tigre@hotmail.com> - 2011-04-15 08:13 -0500
    Re: Understanding global variables. 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-15 13:10 -0500
  Re: Understanding global variables. jake kaiden <jakekaiden@yahoo.com> - 2011-04-15 08:36 -0500
  Re: Understanding global variables. Fily Salas <fs_tigre@hotmail.com> - 2011-04-15 09:14 -0500
  Re: Understanding global variables. jake kaiden <jakekaiden@yahoo.com> - 2011-04-15 09:20 -0500
  Re: Understanding global variables. Fily Salas <fs_tigre@hotmail.com> - 2011-04-16 14:47 -0500

csiph-web