Learning ruby question


#1

I’m having trouble understanding Ruby’s concept of scope. Could
someone explain the difference between the following 2 programs.
They both return the same output “aaaaaaaa”, but I’m just not sure
about self in #1. Is self.day and self.title referring to and setting
class variables or are they instance variables? Thanks in advance.

1.

class Session
attr_accessor :day, :title

def initialize()
self.day = “aaaaaaaa”
self.title = “bbbbb”
end
end

s=Session.new
puts s.day
###################

2.

class Session
attr_accessor :day, :title

def initialize()
@day = “aaaaaaaa”
@title = “bbbbb”
end
end

s=Session.new
puts s.day
###################


#2

In both cases you’re setting instance variables. Class variables are
designated with ‘@@’, and instance variables are usually designated
with ‘@’. But as you’ve seen, you can also set instance variables up
using the ‘self’ reference, which is just a reference to the object
receiving the message. Without the ‘self’ in #1, day and title would
wind up being local variables that would fall out of scope as soon as
initialize() ended.

If you’re familiar with Java, you can think of ‘self’ as ‘this’.

As a thought experiment, what do you think the following code will do?

class Session
attr_accessor :day, :title
def initialize()
self.day = ‘aaa’
self.title = ‘bbb’
end
def say_day
puts @day # Accessing day like any other instance variable, with
‘@’. Think it’ll work?
end
end
s = Session.new
s.say_day


#3

Great thanks. So in my 2 examples above - the code is functionally
the same. You can SET instance variables within a class using either
@var = foo OR self.var = foo

As for your example, based on what I’ve said above - it appears you
can also GET instance variables using self.var or @var - so the output
should be: aaa

Is that correct?

Thanks again.


#4

On 4/28/07, jim removed_email_address@domain.invalid wrote:

Great thanks. So in my 2 examples above - the code is functionally
the same. You can SET instance variables within a class using either
@var = foo OR self.var = foo

As for your example, based on what I’ve said above - it appears you
can also GET instance variables using self.var or @var - so the output
should be: aaa

Is that correct?

That is correct. But don’t take my word for it - run it and see what it
does. :slight_smile:

The best way to learn how all this stuff works is to play with it. If
you think something might work a certain way, try it and see. If it
doesn’t do what you expected, find out why. Interactive Ruby (irb) is
your friend.


Bill K.