Accessing class instance variables from an instance?

Hi there,

I’m writing a class to encapsulate a ‘job’. The job will have variables
such as name, id, resources, dependencies etc and some of these will be
common across all instances. I’d like to be able to set these common
variables once and not have to repeat it for every instance. What’s the
best way of accomplishing this?

So far I’ve seen a lot of articles that steer you towards using class
instance variables instead of class variables but I can’t find examples
of how to use these from within an instance. Is that possible?

Thanks.

An instance variable is prefaced by @, where a class variable is
prefaced by @@. Here’s a small example:

class Thingy
@@thingies = 0
def initialize(name)
@my_name = name
@@thingies += 1
puts “A new thingy is here!”
end

def whatsMyName
puts “This thingy is named ‘#{@my_name}’.”
end

def howMany?
puts “So far you have created #{@@thingies} thingies.”
end
end

The @@thingies class variable is shared by all instances of the class.
Changing that variable in any one of the classes will change it for all
of them.

Is this what you were looking for?

I re-read your post and I don’t think it is, but I think I’m not clear
on what you’re looking for that’s different. Maybe using constants
within the class?

class OtherThingy
CONSTANT_VAR = 5
def whatIsTheConst
p CONSTANT_VAR
end
end

Like that?

On Dec 20, 2011, at 12:26 PM, Khat H. wrote:

Changing that variable in any one of the classes will change it for all
of them.

Is this what you were looking for?

I think he is looking for class instance variables.

class Foo
@class_ivar = 3

def self.class_ivar() @class_ivar; end

def bar(a)
puts “#{a} + #{self.class.class_ivar} = #{a +
self.class.class_ivar}”
end
end

foo = Foo.new
foo.bar(6) # 6 + 3 = 9

cr

Isn’t that just a more complicated way of doing roughly the same thing?
Are there advantages or disadvantages involved in using one or the
other?

That’s interesting. I never considered how they’d behave under
inheritance. Has there been a discussion about changing the behavior so
that the subclasses don’t alter the superclass variable? (Like the
subclass would copy in the superclass var at definition but it would be
a separate instance from the superclass object.)

Class variables are bad. Usually.

Actually, now that I’m thinking about it the existing behavior sort of
what makes more sense. I’d think that subclasses would be better
instantiating their own class vars rather than expecting a unique copy
of the superclass var. I can see why you’d want the class instance vars
rather than modifying the existing mechanic. On the other hand, maybe a
new variable type to encapsulate the behavior of a class instance var in
the way that it’s being used here would be something worth discussing?

I don’t completely understand the script there (I don’t know some of
those methods you’re calling), but it looks like it does what I’m
thinking of. A class accessor would be better than a new var type, I
agree.

On Tue, Dec 20, 2011 at 9:42 PM, Khat H. [email protected]
wrote:

I don’t see any point in that, class ivars seem sufficient to me. What
would be nice, though, is an attr_accessor equivalent that defines
methods
for both the class and instance.

(overly simple example)

class Class
def whatever_accessor(meth_name)
delegate_to_class meth_name
singleton_class.instance_eval do
attr_accessor meth_name
end
end

def delegate_to_class(meth_name)
define_method meth_name do |*args, &block|
self.class.send meth_name, *args, &block
end
end
end

class Foo
whatever_accessor :bar
self.bar = :baz
end

Foo.new.bar # => :baz

<<self is very bad because it starts an multiline string

allways do << self with an " "

On Wed, Dec 21, 2011 at 11:57, Hans M. [email protected] wrote:

<<self is very bad because it starts an multiline string

allways do << self with an " "

Huh?

class "Foo" isn’t valid syntax for a class definition, so the presence
of
“class” disambiguates it.

class X
class <<self
def foo
:foo
end
end

class << self
def bar
:bar
end
end
end

X.foo #=> :foo
X.bar #=> :bar

(But in this case, I think def self.foo is better.)

On Wed, Dec 21, 2011 at 5:34 AM, Josh C. [email protected]
wrote:

On Tue, Dec 20, 2011 at 9:42 PM, Khat H. [email protected] wrote:

Actually, now that I’m thinking about it the existing behavior sort of
what makes more sense. I’d think that subclasses would be better
instantiating their own class vars rather than expecting a unique copy
of the superclass var. I can see why you’d want the class instance vars
rather than modifying the existing mechanic. On the other hand, maybe a
new variable type to encapsulate the behavior of a class instance var in
the way that it’s being used here would be something worth discussing?

I opt for completely removing class variables because they lead to
confusion without end. I don’t see the need for a new type of
variable either. For one, it is an open question if state really
should be managed on the class level. It may be much more appropriate
for Shareed to have a container object which holds a number of
instances and manages common state. If you need that state in
instances you can always have a backward reference to the container.
(You need that anyway if you want to avoid joining multiple containers
for a 1:n relationship.) If state is managed by the class then you
cannot partition the set of instances. And in case of this thread it
seems state is better not held in the class instance, because that
should manage class state while here we are talking about state which
is common to all instances. Just because it’s easy to do or
convenient does not mean that storing this in the class is necessary a
good idea.

I don’t see any point in that, class ivars seem sufficient to me. What
would be nice, though, is an attr_accessor equivalent that defines methods
for both the class and instance.

I find that a bad idea: this easily leads to confusion and if you want
the same attribute in the class and all instances then you better make
that explicit. This should be a very rare case anyway. The only
thing which comes to mind where this seems remotely useful would be
default values for fields. But in this case I’d rather name fields
differently because they mean something different:

class Foo
class <<self
attr_accessor :name_default
end

attr_writer :name

def name
@name || self.class.name_default
end
end

irb(main):025:0> Foo.name_default = “X”
=> “X”
irb(main):026:0> f = Foo.new
=> #Foo:0x1018c06c
irb(main):027:0> f.name
=> “X”
irb(main):028:0> f.name = “bar”
=> “bar”
irb(main):029:0> f.name
=> “bar”
irb(main):030:0> Foo.name_default
=> “X”

Kind regards

robert

On Wed, Dec 21, 2011 at 2:50 AM, Robert K.
[email protected]wrote:

the way that it’s being used here would be something worth discussing?
cannot partition the set of instances. And in case of this thread it

end
=> “X”

Kind regards

robert


remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

Yeah, sorry, it was late. The need I actually come across isn’t state
based, but functionality based. For example, HTTParty’s get method. From
outside it’s nice to be able to say HTTParty.get(...) but from inside
they don’t want to have to say self.class.get(...) so that is an
example
of a class level method that should be available to instances without
having to go find the class. I find that need occasionally. Or sometimes
I’m looking at some method and realizing it really could be a class
method,
and that no one can use it without instantiating, but it’s pretty
obnoxious
to have to instantiate a class just to call some method that doesn’t
depend
on instances.

On Wed, Dec 21, 2011 at 3:08 PM, Josh C. [email protected]
wrote:

Yeah, sorry, it was late. The need I actually come across isn’t state
based, but functionality based. For example, HTTParty’s get method. From
outside it’s nice to be able to say HTTParty.get(...) but from inside
they don’t want to have to say self.class.get(...) so that is an example

You can also say HTTParty.get(…) inside instance methods.

of a class level method that should be available to instances without
having to go find the class. I find that need occasionally. Or sometimes
I’m looking at some method and realizing it really could be a class method,
and that no one can use it without instantiating, but it’s pretty obnoxious
to have to instantiate a class just to call some method that doesn’t depend
on instances.

Well, then make it a class method. That has the added advantage that
you make the call explicit in instance methods which use it and it is
immediately clear that this method does not manipulate instance state.

I think this make-a-class-method-be-callable-as-instance-method looks
convenient on first sight but on second sight it may just be
obfuscation.

Kind regards

robert

<<self is very bad because it starts an multiline string

In this case, it is not.

Concerning an attr for civ’s, would it really be detrimental, though?
True it’s something that would very rarely be used, but it almost feels
like it’s something that belongs there. I guess what I mean is, if
attr_accessor exists it feels to me like there should be a sort of
class-level equivalent. Maybe that’s just me, though. This has
somewhat moved beyond my depth. I’m grateful for the conversation,
though. I’ll be looking some of this up later when I have the time.

On Wed, Dec 21, 2011 at 6:48 PM, Khat H. [email protected]
wrote:

Concerning an attr for civ’s, would it really be detrimental, though?

Do you mean an attr_accessor like method for a class instance itself?

True it’s something that would very rarely be used, but it almost feels
like it’s something that belongs there. I guess what I mean is, if
attr_accessor exists it feels to me like there should be a sort of
class-level equivalent. Maybe that’s just me, though. This has
somewhat moved beyond my depth.

If you mean such a method then yes, that might be a reasonable thing to
have.

Kind regards

robert

I once spent almost two hours locating a bug.

In old ruby code I wrote years ago.

Turned out I used class variables.

I then also understood that there was no need for me to use them.

Since I wasted time, and also had a bug, I decided that day to no longer
use class variables at all.

There are a very few use cases where they may seem not totally useless,
but so far I myself did not need them at all. And I follow a philosophy
that less (code) is more.

Hi Robert and Josh,

On 22/12/11 00:49, Robert K. wrote:

having to go find the class. I find that need occasionally. Or sometimes
convenient on first sight but on second sight it may just be
obfuscation.

Kind regards

robert

I’ve run into this kind of thing before, and it does impact me
regularly. Having said that, I know my C++ background (which allows
this) biases me somewhat on the issue. :wink:

I tend to steer away from “Foo.bar” style calls inside class Foo for the
following reason- it complicates refactoring. If you determine that a
class would benefit from being split (perhaps because another class has
common functionality and you want it to share a common base), then you
have to selectively rename all of the calls you have made to point to
the correct class. Sure, it’s not hard, and doesn’t take too long, but
when you’re refactoring something for the sake of something else you
have developed, not having to deal with additional chores to make it
work makes it less likely that you’ll stuff something up in the process.
A similar problem arises with renaming the class, but admittedly the
solution tends to be far easier.

For that reason, I’d instead use “class.bar” calls, if it were possible,
which it is not, which brings us to “self.class.bar”. I do this as you
can’t always tell ahead of time when you’ll need to refactor something
to pull out a base class, and so I’ll assume that (almost) all of the
classes I work on could be subject to such changes later in its
lifetime. If you could tell beforehand, you would have designed it that
way in the first place. :slight_smile: Now, if you have a class method that is used
both inside and out, but mostly inside (and regularly), it’s a pain to
have to write “self.class.bar” each time you want to call “bar”.
Incidentally, for “bar”, I have a specific method in mind for something
I have been working on (ie. a real-world problem), that makes the most
sense as a class method, since it works entirely off the arguments and
carries no state. The call in question has very specific structured
input requirements, and is called extremely frequently inside the class,
and occasionally outside.

In my case, I ended up solving it by adding an “abar” method that just
called “self.class.bar”, although using it that way does feel a bit
silly, and makes the code less readable (an observer might ask what the
difference between “bar” and “abar” is, for example).

Anyway, I just thought I’d share my particular experience. It’s not hard
to work around, but there are definitely good reasons to want to make it
work that way. It falls under the area of a “quirk” for me, but that is
of course just my personal experience based on my personal experience.

That has the added advantage that
you make the call explicit in instance methods which use it and it is
immediately clear that this method does not manipulate instance
state.

There are definitely cases where this could be advantageous, but there
are also cases where this is not necessary or desirable. In general, I
would personally say that if a particular mechanism is sometimes
beneficial, but sometimes not, it is better to leave it up to the person
writing the code to emphasise the mechanism where it is appropriate, and
de-emphasise where it is not. For example, sometimes it is beneficial to
be specific about the particular class of an object (or its
capabilities), but would that justify requiring every method call to be
prefixed by the class name, every time? I would say not. There are times
where being specific about it would be beneficial, but in the remaining
cases it would clutter up the code unnecessarily.

I think in the situation I outlined above, and possibly also in Josh’s
case, it falls in the realm of clutter. This does not, of course, take
away from the fact that in some situations it would be important, or
absolutely essential, to explicitly convey that the instance state will
not be manipulated. I know that I have certainly run into this case as
well- I won’t bother with a personal anecdote as I suspect you also
already know of many cases where it is extremely beneficial already. :slight_smile:

I guess what I am saying is that if something is sometimes beneficial,
and sometimes detrimental, that enforcing it is not always the best
idea, but providing an optional means to make it explicit is beneficial.
I do not believe that is a good idea in general to either force a
mechanism that is only sometimes useful, or argue that as the mechanism
is sometimes important, that having a means to conveniently avoid the
mechanism when it is detrimental is not justified. There are of course
always all sorts of tradeoffs when designing a language- perhaps the
particular feature Josh and I would find beneficial is not readily
possible for some technical reason.

All IMHO.

Garth

PS. Wow, that message was a bit longer than I had planned. :wink:

On Thu, Dec 22, 2011 at 2:09 AM, Garthy D
[email protected] wrote:

refactoring something for the sake of something else you have developed, not
if you have a class method that is used both inside and out, but mostly
and makes the code less readable (an observer might ask what the difference
between “bar” and “abar” is, for example).

A better alternative would be to do this:

class Object
def my_class; self.class end
end

Then you do not need to do

Foo.bar
self.class.bar

but instead you can do

my_class.bar

which seems a lot clearer to me while avoiding the nasty “self.class”.
Maybe someone else can think of a better (presumably: shorter) name
than #my_class.

Anyway, I just thought I’d share my particular experience. It’s not hard to
work around, but there are definitely good reasons to want to make it work
that way. It falls under the area of a “quirk” for me, but that is of course
just my personal experience based on my personal experience.

I guess my main point is that making a method call appear to be on the
local instance which in fact is done on another instance is
misleading. For the reader it is better to at least signal that #foo
is not invoked on self but rather on another instance. For that you
need a method or a variable reference.

particular class of an object (or its capabilities), but would that justify
requiring every method call to be prefixed by the class name, every time? I
would say not. There are times where being specific about it would be
beneficial, but in the remaining cases it would clutter up the code
unnecessarily.

We differ in the estimation about the distribution of useful and
harmful. I’d say obfuscating a method is invoked on another instance
does more harm than good so the default should be to not make it too
easy. This forces people to know what they are doing when they do it.
As an example: you can modify instance variables of another instance
but it is deliberately made clumsy (#set_instance_variable etc.)
although possible.

I think in the situation I outlined above, and possibly also in Josh’s case,
it falls in the realm of clutter. This does not, of course, take away from
the fact that in some situations it would be important, or absolutely
essential, to explicitly convey that the instance state will not be
manipulated. I know that I have certainly run into this case as well- I
won’t bother with a personal anecdote as I suspect you also already know of
many cases where it is extremely beneficial already. :slight_smile:

That’s the point: OO is mostly about the state of instances and its
changes. Everything that helps keep clear what’s happening is good
IMHO.

I guess what I am saying is that if something is sometimes beneficial, and
sometimes detrimental, that enforcing it is not always the best idea, but
providing an optional means to make it explicit is beneficial. I do not
believe that is a good idea in general to either force a mechanism that is
only sometimes useful, or argue that as the mechanism is sometimes
important, that having a means to conveniently avoid the mechanism when it
is detrimental is not justified. There are of course always all sorts of
tradeoffs when designing a language- perhaps the particular feature Josh and
I would find beneficial is not readily possible for some technical reason.

There are no technical obstacles here defining instance methods which
access class state. I just happen to believe that the tradeoff fall
on the side that we do not want to have such a feature because the
convenience of the writer is the pain of the reader of the code.

All IMHO.

+1

PS. Wow, that message was a bit longer than I had planned. :wink:

:slight_smile:

Kind regards

robert