Forum: Ruby class 'initialize' method not working ???

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Tom C. (Guest)
on 2009-01-23 22:11
(Received via mailing list)
I'm baffled by this error, after a hour+ of experimentation with
solutions. I assume it's a compiler error (right term in Ruby?), as I'm
not even getting access to ruby-debug.

Code snippet:
=======
def main

  opdb = Open_db.new( [1,2,3] )

end

class Open_db
  def initialize( dblist )
    @dbs = dblist
  end

  @dbs.each do |cnt|  # <= line producing the error
    db_lbl = cnt[0]
    db_nm = cnt[1]
  end
end

%w(rubygems ruby-debug readline strscan logger fileutils).each{ |lib|
require lib }
Debugger.start
debugger # call to ruby-debug

main # ...initiate execution (at this point all dependencies are
resolved)

# end file
=========

Error msg: setnet-xa.rb:12: undefined method `each' for nil:NilClass
(NoMethodError)

It appears that @dbs is not getting initialized, but I cannot why not.

Any help would be much appreciated!

Tom

--

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom C., MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< removed_email_address@domain.invalid >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lucas (Guest)
on 2009-01-23 22:35
(Received via mailing list)
Remove the 'end' after @dbs = dblist
Florian G. (Guest)
on 2009-01-23 23:00
(Received via mailing list)
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


On Jan 23, 2009, at 9:09 PM, Tom C. wrote:

> I'm baffled by this error, after a hour+ of experimentation with
> solutions. I assume it's a compiler error (right term in Ruby?), as
> I'm not even getting access to ruby-debug.


Its not a ruby error.

>     @dbs = dblist
>   end
>
>   @dbs.each do |cnt|  # <= line producing the error
>      db_lbl = cnt[0]
>      db_nm = cnt[1]
>   end
> end
>

That might be irritating at first, but you actually refer to two
different variables hier.

First, in #initialize, you refer to an instance variable called @dbs
in the context of an object instance (the instance of Open_db).

The second part with @dbs, which is evaluated when loading the class
definition is refering to an instance variable in the context of a
class definition (as classes in ruby are objects by themselves, this
is perfectly valid). The problem is, that in class context, @dbs has
not been initialized. Unitialized instance variables are nil by
definition => calling each on it fails.

Feel free to ask further questions.

Regards,
Florian

- --
Florian G.

smtp:   removed_email_address@domain.invalid
jabber: removed_email_address@domain.invalid
gpg:    533148E2

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)

iEYEARECAAYFAkl6L9sACgkQyLKU2FMxSOJU6ACfZQlLGOXbY8Rq3ChHRfpOWWBy
c5EAoJ9dVgjh4EagntgbEyr8Z1DGn8kq
=46uW
-----END PGP SIGNATURE-----
Tom C. (Guest)
on 2009-01-24 00:00
(Received via mailing list)
Florian G. wrote:
>
>> class Open_db
>
> not been initialized. Unitialized instance variables are nil by
> smtp:   removed_email_address@domain.invalid
>
>
Florian, thanks for your response. It's a bit of a mind blower, although
I think I understand it. I continue to discover that classes have a
number of subtleties which my reliable old workhorse procedural Ruby
(all I've done until this week) simply doesn't have. It's fun learning
about them, though...mostly!

Here's a small class from the same project I'm working on  - and it
works fine. The only structural difference I can see is that ALL code in
this second class is wrapped in method definitions. So, if I understand
you correctly, the code in the second method below is NOT part of the
class definition evaluation, but is subsumed under the definition of a
method, thus preventing the problem I was having with the other code. My
question: Do I have this right?

# dump setnet data to files
class Dump_db
  def initialize( logging_now, log, db_array )
    @logging_now = logging_now
    @log = log
    @db_array = db_array
  end
  def dump
    @db_array.each do |cnt|
      begin #start error trapping
        dbnm = cnt[ 0 ]
        dbobj = cnt[ 1 ]
        if @logging_now: @log.info( dbnm + ' output to file started' )
end
        fn = dbnm + '.yml'
        open( fn, 'w' ) {|i| YAML.dump( dbobj, i )}
        status = ( ( dbobj.length - 1 ).to_s + dbnm +' written to file'
)
        puts "> "+status
        if @logging_now: @log.info status end
      rescue Exception => e
        if @logging_now: @log.error( "#{e}" ) end
        if @logging_now: @log.error e.backtrace end #pinpoints error
location end
        puts "> ERROR logged to log file..."
        result = nil
      end
    end
  end
end

This is all very interesting, and if I understand it right, it's
something that I have not seen pointed out in any of the references I've
been studying. Kind of a major point.

Thanks again for you help (and you also, Lucas).

Tom

--

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom C., MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< removed_email_address@domain.invalid >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
David A. Black (Guest)
on 2009-01-24 00:20
(Received via mailing list)
Hi Tom --

On Sat, 24 Jan 2009, Tom C. wrote:

>>
>>>
>>>
>> valid). The problem is, that in class context, @dbs has not been
>>
>> -----END PGP SIGNATURE-----
> second class is wrapped in method definitions. So, if I understand you
> correctly, the code in the second method below is NOT part of the class
> definition evaluation, but is subsumed under the definition of a method, thus
> preventing the problem I was having with the other code. My question: Do I
> have this right?

[snip]

There's another way to look at this, which might be helpful. The way
you tell which object an instance variable belongs to is simple: it
belongs to self. That's always true. Whenever you see:

   @x

if you know what self is at that moment, you know whose instance
variable @x is.

So, for example:

   class MyClass
     puts "self is: #{self}"
     @x = 1
   end

   Output:  self is MyClass

self, in this context, is the class object MyClass itself. That means
that @x belongs to MyClass; it is an instance variable of MyClass, in
MyClass's capacity as an instance of Class (which all classes are).

Here, self is different:

   class MyClass
     def a_method
       puts "self is: #{self}"
       @x = 1
     end
   end

   obj = MyClass.new
   obj.a_method      # self is: #<MyClass:0x26032c>

In one context, self is a class object called MyClass. In the other
context (inside a method definition), self is an instance of MyClass.
(It's sort of "an instance to be named later"; the method only gets
executed once an instance of MyClass exists and calls it.) Classes and
their instances do not share instance variables, any more than any
other objects do (which is to say, not at all).

I've always said that the answer to 75% of all questions about Ruby
is: "Because classes are objects." :-) That's the central point here.
A class *itself* can have instance variables because, in addition to
be an "object factory", a class is also, in its own right, an object.

> This is all very interesting, and if I understand it right, it's something
> that I have not seen pointed out in any of the references I've been studying.
> Kind of a major point.

<plug>Check out "The Well-Grounded Rubyist" -- it's definitely in
there :-)</plug>


David

--
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2)

http://www.wishsight.com => Independent, social wishlist management!
Tom C. (Guest)
on 2009-01-24 00:37
(Received via mailing list)
David A. Black wrote:
>>>
>>>>
>>>>      db_lbl = cnt[0]
>>>
>>> Florian
>>>
>> It's fun learning about them, though...mostly!
>
>
>
>   obj.a_method      # self is: #<MyClass:0x26032c>
> A class *itself* can have instance variables because, in addition to
> David
>
Really cool David. Very lucid. This week I've begun to see whole new
levels of Ruby's internal logic which heretofore had escaped me. Great!

I've been enjoying your and Dave T.'s talk at RubyConf 2008 on
"what's new in Ruby 1.9" (title gloss). Only part of the way through it.

What a fantastic resource that website is -

http://rubyconf2008.confreaks.com/

Thanks to Robert D. for THAT one!!

Finally - I wasn't aware of your book. Thanks for the heads up. Amazon
says it's not out yet, but it IS (in early release form, anyway, and is
available here -

http://www.manning.com/black2/

In downloadable form (hoorah!), yet.

Is that the complete outline - is it all written? No chapter on Ruby and
world politics, or Ruby and improving energy production efficiency?

t.



--

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom C., MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< removed_email_address@domain.invalid >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Rob B. (Guest)
on 2009-01-24 00:42
(Received via mailing list)
Tom,
Since it looks like your Ruby code is written in a distinctly non-Ruby-
esque style, I thought I'd show you how I'd expect most Rubyists would
write your Dump_db

On Jan 23, 2009, at 4:57 PM, Tom C. wrote:

> part of the class definition evaluation, but is subsumed under the
>   @db_array.each do |cnt|
>       if @logging_now: @log.info status end
>
> This is all very interesting, and if I understand it right, it's
> something that I have not seen pointed out in any of the references
> I've been studying. Kind of a major point.
>
> Thanks again for you help (and you also, Lucas).
>
> Tom


# dump setnet data to files
class Dump_db
   def initialize(db_array, log=nil)
     @db_array = db_array
     @log = log
   end

   def dump
     @db_array.each do |dbnm,dbobj|
       begin #start error trapping
         @log.info( dbnm + ' output to file started' ) if @log
         open(dbnm + '.yml', 'w' ) {|i| YAML.dump( dbobj, i )}
         status = ( ( dbobj.length - 1 ).to_s + dbnm +' written to
file' )
         puts "> "+status
         @log.info status if @log
       rescue Exception => e
         if @log
           @log.error( "#{e}\n  " )
           @log.error e.backtrace.join("\n  ")
           puts "> ERROR logged to log file..."
         end #pinpoints error location end
       end
     end
   end
end

Note in particular:
   The order of arguments to Dump_db.new (and thus, initialize) have
changed.  If you don't intend to log, you can just say:
Dump_db.new(your_db_array)

   There was no separation between @log and @logging_now, so just rely
on whether a log was given.

   The use of a : to mean "then" has been deprecated.  However, you
can put a conditional modifier at the end of a statement:
     if @log
       @log.info( "stuff" )
     end
   is exactly:
     @log.info( "stuff" ) if @log

   You probably want to separate the lines in the backtrace, so look
at what I've done to the rescue block.

   Typically, you don't rescue Exception, but rather StandardError.
That's the default, too, so you can just:
     rescue => e
   to mean
     rescue StandardError => e
   since most of the exceptions that are not inherited from
StandardError you won't want to catch in most cases.

-Rob

Rob B.    http://agileconsultingllc.com
removed_email_address@domain.invalid
David A. Black (Guest)
on 2009-01-24 00:45
(Received via mailing list)
Hi --

On Sat, 24 Jan 2009, Tom C. wrote:

> Thanks to Robert D. for THAT one!!
> world politics, or Ruby and improving energy production efficiency?
That is indeed the outline, and it is all written. (I'll cover the
geopolitical ramifications of Ruby in the sequel :-) I'm about halfway
through reviewing copy-edited/tech-edited (thanks, Greg Brown!)
chapters. Then proofreading, dealing with last-minute whatever
(there's always something!), and then it should be good to go.


David

--
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2)

http://www.wishsight.com => Independent, social wishlist management!
Tom C. (Guest)
on 2009-01-24 01:03
(Received via mailing list)
Rob B. wrote:
>> procedural Ruby (all I've done until this week) simply doesn't have.
>> # dump setnet data to files
>>       if @logging_now: @log.info( dbnm + ' output to file started' ) end
>>       result = nil
>>
>   def dump
>           @log.error e.backtrace.join("\n  ")
> Dump_db.new(your_db_array)
>     @log.info( "stuff" ) if @log
> StandardError you won't want to catch in most cases.
>
> -Rob
>
> Rob B.        http://agileconsultingllc.com
> removed_email_address@domain.invalid
>
>
Wow, this IS my day for Ruby.study - I'm deeply appreciative. Learning
the idiom takes time and exposure, but it's usually worth it (at least
in Spanish and French...and English!) I will carefully study what you've
written, you may be sure. It won't be wasted - far from it.

Essentially all my code is written in direct response to a pressing
need, so I'm always trying simply to 'get it working and move on'. I
really NEED what this current project will do for me, and have been
needing it for weeks. That pressing need can interfere with pure
learning, alas. My code reflects my background in procedural programming
- again, always in response to some pressing need. But I'm very
interested in the elegance of "The Ruby Way" - it's what brought me to
Ruby in the first place.

Again, thanks for your thought, time, and effort - you've given me a
considerable gift. I will make every attempt to carry what I'm learning
today forward into the next code I write (and also will be cleaning up
some already written stuff - need to set a good example for myself!)

t.

--

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom C., MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< removed_email_address@domain.invalid >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This topic is locked and can not be replied to.