[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

When to use instance variables @

Steve Dogers

3/30/2009 7:53:00 PM

Hi, I have a couple questions about instance variables in Ruby.
1) do i need to declare them at the top of my class file - I do
understand the accessors are automatic but I'm not sure if I can just
pull a @product in the middle of a function

2) do i need to use the @ to refer to them in the class. Would it work
without the @, and if so, how does it differentiate them from local
vars?

3) I've seen code where just below the class declaration, objects are
instantiated like product = Product.new - I don't see a @ sign, does
that mean it's a local var? How can a local var even exist at the class
level, outside a function?


Many thanks!
--
Posted via http://www.ruby-....

18 Answers

Phrogz

3/30/2009 8:06:00 PM

0

On Mar 30, 1:52 pm, Steve Dogers <stevedog...@gmail.com> wrote:
> Hi, I have a couple questions about instance variables in Ruby.
> 1) do i need to declare them at the top of my class file - I do
> understand the accessors are automatic but I'm not sure if I can just
> pull a @product in the middle of a function

No. You can ask for any instance variable at any time - if no value
has ever been set, you will get nil back. You can set any instance
variable at any time. A common idiom is:
@foo ||= 42
which is the same as "@foo = @foo || 42" which technically means "Set
@foo to 42 if is it currently false or nil"; when you're not dealing
with an instance variable that deals in boolean values, however, it
basically means "Set @foo to 42 unless I already set it to some
value."


> 2) do i need to use the @ to refer to them in the class. Would it work
> without the @, and if so, how does it differentiate them from local
> vars?

It does not work without the @. You must use it everywhere, even when
using something like:
variable_name = "foo"
instance_variable_set( :"@#{variable_name}", 42 )


> 3) I've seen code where just below the class declaration, objects are
> instantiated like product = Product.new - I don't see a @ sign, does
> that mean it's a local var? How can a local var even exist at the class
> level, outside a function?

Class 'declarations' aren't quite what you think they are. They're
actually code that is executed. Try this on for size:

msg = "outside"
puts "#{msg} class"
class Foo
msg = "inside"
puts "#{msg} class"
end
puts "#{msg} class"

Note in particular the last message; the output "outside class" lets
you know that there are two local variables with the same name, in
their own scopes.

Michael Malone

3/30/2009 8:30:00 PM

0

Steve Dogers wrote:
> Hi, I have a couple questions about instance variables in Ruby.
> 1) do i need to declare them at the top of my class file - I do
> understand the accessors are automatic but I'm not sure if I can just
> pull a @product in the middle of a function
>
No, you don't need to declare them at the top of your file, just before
you use them. It's good practice to initialise each of your class
variables in your constructor, but this is not always possible.
in the middle of a member function, you can just pull a '@product =
something' even if you haven't already defined it, but bugs are harder
to trace if variables start popping up all over the place.
> 2) do i need to use the @ to refer to them in the class. Would it work
> without the @, and if so, how does it differentiate them from local
> vars?
>
Yes, always with the @ that's exactly how their scope is known to the
interpreter.
> 3) I've seen code where just below the class declaration, objects are
> instantiated like product = Product.new - I don't see a @ sign, does
> that mean it's a local var? How can a local var even exist at the class
> level, outside a function?
>
a local var existing at the class level outside a function? That to me
means something like this:

class Klass
product = Product.new

def some_function
nil
end
end

That doesn't make sense to me and has no accessible means (I could be
wrong on this one though). It's valid syntax, but to my understanding,
it will be instantiated and then immediately set for garbage
collection. A subtle note is that if the variable name starts with a
Capital letter, then it is a constant that belongs to that class and has
java-like public scope, so can be referred to by Klass::Constant

Also, you might see some people write code that looks procedural, but
uses @variables and so forth. This is because you are by default in the
Object class's scope. Hmmm, this makes me think that local variables at
the class level should be treated identically as the procedural-like
code at the Object scope. I think I have just confused myself, can
anyone clarify this? (Of course, I'm not actually going to use this
feature, even if it exists, but it would be nice to understand)
>
> Many thanks!
>


=======================================================================
This email, including any attachments, is only for the intended
addressee. It is subject to copyright, is confidential and may be
the subject of legal or other privilege, none of which is waived or
lost by reason of this transmission.
If the receiver is not the intended addressee, please accept our
apologies, notify us by return, delete all copies and perform no
other act on the email.
Unfortunately, we cannot warrant that the email has not been
altered or corrupted during transmission.
=======================================================================


Albert Schlef

3/30/2009 10:01:00 PM

0

Steve Dogers wrote:
> Hi, I have a couple questions about instance variables in Ruby.
> 1) do i need to declare them at the top of my class file

In Ruby you declare nothing. (That's unlike languages like Java, C,
etc., where everything has to be declated before use.)

So, in Ruby you don't declare variables. In fact, you don't even declare
functions and classes. (You "create" them.)

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

Iñaki Baz Castillo

3/30/2009 10:06:00 PM

0

El Martes 31 Marzo 2009, Albert Schlef escribi=C3=B3:
> In Ruby you declare nothing. (That's unlike languages like Java, C,
> etc., where everything has to be declated before use.)

This is not true when using class variables (@@). These need to be "declare=
d"=20
at the beginning of the class:


class KK

@@koko # <-- WRONG since no assignement is done.
# @@koko =3D #SOMETHING# is required.

def show_var
puts "koko =3D #{@@koko}"
end

def set_var(v)
@@koko =3D v
end

end


irb(main):022:0> k=3DKK.new

irb(main):023:0> k.show_var
NameError: uninitialized class variable @@koko in KK

irb(main):024:0> k.set 123
irb(main):025:0> k.show_var
koko =3D 123


=2D-=20
I=C3=B1aki Baz Castillo <ibc@aliax.net>

Joshua Collins

3/30/2009 10:12:00 PM

0

[quote]This is not true when using class variables (@@). These need to be
"declared"
at the beginning of the class:[/quote]

You are incorrect.

On Mon, Mar 30, 2009 at 6:05 PM, I=F1aki Baz Castillo <ibc@aliax.net> wrote=
:

> El Martes 31 Marzo 2009, Albert Schlef escribi=F3:
> > In Ruby you declare nothing. (That's unlike languages like Java, C,
> > etc., where everything has to be declated before use.)
>
> This is not true when using class variables (@@). These need to be
> "declared"
> at the beginning of the class:
>
>
> class KK
>
> @@koko # <-- WRONG since no assignement is done.
> # @@koko =3D #SOMETHING# is required.
>
> def show_var
> puts "koko =3D #{@@koko}"
> end
>
> def set_var(v)
> @@koko =3D v
> end
>
> end
>
>
> irb(main):022:0> k=3DKK.new
>
> irb(main):023:0> k.show_var
> NameError: uninitialized class variable @@koko in KK
>
> irb(main):024:0> k.set 123
> irb(main):025:0> k.show_var
> koko =3D 123
>
>
> --
> I=F1aki Baz Castillo <ibc@aliax.net>
>
>

Iñaki Baz Castillo

3/30/2009 10:31:00 PM

0

El Martes 31 Marzo 2009, Joshua Collins escribi=C3=B3:
> [quote]This is not true when using class variables (@@). These need to be
> "declared"
> at the beginning of the class:[/quote]
>
> You are incorrect.

Perhaps you could detail it a little more.

Yes, surely there are other ways to use class variables without assigning t=
hem=20
a value into the class and out of class methods, but what I mean is that cl=
ass=20
variables are not like instance variables since they must exist prior to be=
ing=20
used. Am I wrong?

=2D-=20
I=C3=B1aki Baz Castillo <ibc@aliax.net>

Joshua Collins

3/30/2009 11:17:00 PM

0

All variables in Ruby (Local, Global, Instance (object), or Class) do not
need to be defined at the beginning of a method.

I believe what we have is a miscommunication on the terminology!

Programing in general, when one defines a variable, then you are telling th=
e
compiler what type of variable it is: String, Integer, Float, etc...

When you set a variable, then you are giving that variable a value.

I will use C++ as an example:

#include <iostream>

int main()
{
using std::cout;
using std::endl;

//Notice how you must define the variable before you set it's value
unsigned short int Width =3D 5;
unsigned short int Length =3D 10;
unsigned short int Area =3D (Width * Length)

cout << "Width: " << Width << endl;
cout << "Length: " << Length << endl;
cout << "Area: " << Area << endl;

return 0;
}

=3D=3D=3D=3D
Width: 5
Length: 10
Area: 500
=3D=3D=3D=3D

In Ruby you set variables, and then ruby auto defines that variable.

In Ruby, do you need to set that variable before calling it? Yes.

In Ruby, do you need to define that variable before setting it? No.


Here is a good way to use a Class variable:

class Square
def initialize
if defined?(@@number_of_squares)
@@number_of_squares +=3D 1
else
#No need to define the variable before it's value is set
@@number_of_squares =3D 1
end
end

def Square.count
@@number_of_squares
end
end

a =3D Square.new
puts Square.count
b =3D Square.new
puts Square.count
c =3D Square.new
puts Square.count

=3D=3D=3D=3D
1
2
3
=3D=3D=3D=3D

I hope that clarifies some confusion on the terminology being used, and it
helps in clearing up the confusion on how to use a Class variable in Ruby ;=
)

Peace
JC

On Mon, Mar 30, 2009 at 6:30 PM, I=F1aki Baz Castillo <ibc@aliax.net> wrote=
:

> El Martes 31 Marzo 2009, Joshua Collins escribi=F3:
> > [quote]This is not true when using class variables (@@). These need to =
be
> > "declared"
> > at the beginning of the class:[/quote]
> >
> > You are incorrect.
>
> Perhaps you could detail it a little more.
>
> Yes, surely there are other ways to use class variables without assigning
> them
> a value into the class and out of class methods, but what I mean is that
> class
> variables are not like instance variables since they must exist prior to
> being
> used. Am I wrong?
>
> --
> I=F1aki Baz Castillo <ibc@aliax.net>
>
>

Iñaki Baz Castillo

3/30/2009 11:28:00 PM

0

El Martes 31 Marzo 2009, Joshua Collins escribi=C3=B3:
> All variables in Ruby (Local, Global, Instance (object), or Class) do not
> need to be defined at the beginning of a method.

I didn't say "at the beginning of a method", but "at the beginning of a cla=
ss"=20
(anyhow I was also wrong XD).




> In Ruby, do you need to set that variable before calling it? Yes.

Well, this is different for class variables and instance variables:

=2D-------------
irb> @non_existing_instance_variable
nil

irb> @@non_existing_class_variable
NameError: uninitialized class variable @@non_existing_class_variable in=20
Object
from (irb):2
from /usr/bin/irb:12:in `<main>'
=2D-------------

What I mean is that class variables MUST be defined (not declared, of cours=
e)=20
before *reading* them, while an instance variable returns nil if it's not s=
et=20
yet.



> #No need to define the variable before it's value is set
> @@number_of_squares =3D 1

Yes, please note that I said:
=2D---------
This is not true when using class variables (@@). These need to be "declare=
d"=20
at the beginning of the class
=2D---------
(note the "declared" between "" XD)


Regards.


=2D-=20
I=C3=B1aki Baz Castillo <ibc@aliax.net>

Joshua Collins

3/30/2009 11:33:00 PM

0

Ah right.

I totally forgot about instance auto set to nil ;)

I see where you were coming from now.

On Mon, Mar 30, 2009 at 7:27 PM, I=F1aki Baz Castillo <ibc@aliax.net> wrote=
:

> El Martes 31 Marzo 2009, Joshua Collins escribi=F3:
> > All variables in Ruby (Local, Global, Instance (object), or Class) do n=
ot
> > need to be defined at the beginning of a method.
>
> I didn't say "at the beginning of a method", but "at the beginning of a
> class"
> (anyhow I was also wrong XD).
>
>
>
>
> > In Ruby, do you need to set that variable before calling it? Yes.
>
> Well, this is different for class variables and instance variables:
>
> --------------
> irb> @non_existing_instance_variable
> nil
>
> irb> @@non_existing_class_variable
> NameError: uninitialized class variable @@non_existing_class_variable in
> Object
> from (irb):2
> from /usr/bin/irb:12:in `<main>'
> --------------
>
> What I mean is that class variables MUST be defined (not declared, of
> course)
> before *reading* them, while an instance variable returns nil if it's not
> set
> yet.
>
>
>
> > #No need to define the variable before it's value is set
> > @@number_of_squares =3D 1
>
> Yes, please note that I said:
> ----------
> This is not true when using class variables (@@). These need to be
> "declared"
> at the beginning of the class
> ----------
> (note the "declared" between "" XD)
>
>
> Regards.
>
>
> --
> I=F1aki Baz Castillo <ibc@aliax.net>
>
>

Iñaki Baz Castillo

3/30/2009 11:44:00 PM

0

El Martes 31 Marzo 2009, Joshua Collins escribi=C3=B3:
> Ah right.
>
> I totally forgot about instance auto set to nil ;)

Yes, I just wanted to point that, but I chose a wrong and prohibited word i=
n=20
Ruby ("declare") XDDD

Regards.

=2D-=20
I=C3=B1aki Baz Castillo <ibc@aliax.net>