[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

class 'initialize' method not working ???

Tom Cloyd

1/23/2009 8:09:00 PM

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 Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< tc@tomcloyd.com >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


8 Answers

Lucas

1/23/2009 8:33:00 PM

0

[Note: parts of this message were removed to make it a legal post.]

Remove the 'end' after @dbs = dblist

On Fri, Jan 23, 2009 at 6:09 PM, Tom Cloyd <tomcloyd@comcast.net> 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.
>
> 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 Cloyd, MS MA, LMHC - Private practice Psychotherapist
> Bellingham, Washington, U.S.A: (360) 920-1226
> << tc@tomcloyd.com >> (email)
> << TomCloyd.com >> (website) << sleightmind.wordpress.com >> (mental
> health weblog)
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
>
>


--
xucros.com

Florian Gilcher

1/23/2009 8:58:00 PM

0

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1


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

> I'm baffled by this error, after a hour+ of experimentation with =20
> solutions. I assume it's a compiler error (right term in Ruby?), as =20=

> I'm not even getting access to ruby-debug.


Its not a ruby error.

> Code snippet:
> =3D=3D=3D=3D=3D=3D=3D
> def main
>
> opdb =3D Open_db.new( [1,2,3] )
>
> end
>
> class Open_db
> def initialize( dblist )
> @dbs =3D dblist
> end
>
> @dbs.each do |cnt| # <=3D line producing the error
> db_lbl =3D cnt[0]
> db_nm =3D cnt[1]
> end
> end
>

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

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

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

Feel free to ask further questions.

Regards,
Florian

- --
Florian Gilcher

smtp: flo@andersground.net
jabber: Skade@jabber.ccc.de
gpg: 533148E2

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

iEYEARECAAYFAkl6L9sACgkQyLKU2FMxSOJU6ACfZQlLGOXbY8Rq3ChHRfpOWWBy
c5EAoJ9dVgjh4EagntgbEyr8Z1DGn8kq
=3D46uW
-----END PGP SIGNATURE-----

Tom Cloyd

1/23/2009 9:57:00 PM

0

Florian Gilcher wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
>
> On Jan 23, 2009, at 9:09 PM, Tom Cloyd 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.
>
>> 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
>>
>
> 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 Gilcher
>
> smtp: flo@andersground.net
> jabber: Skade@jabber.ccc.de
> gpg: 533148E2
>
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.8 (Darwin)
>
> iEYEARECAAYFAkl6L9sACgkQyLKU2FMxSOJU6ACfZQlLGOXbY8Rq3ChHRfpOWWBy
> c5EAoJ9dVgjh4EagntgbEyr8Z1DGn8kq
> =46uW
> -----END PGP SIGNATURE-----
>
>
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 Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< tc@tomcloyd.com >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


David A. Black

1/23/2009 10:18:00 PM

0

Hi Tom --

On Sat, 24 Jan 2009, Tom Cloyd wrote:

> Florian Gilcher wrote:
>> -----BEGIN PGP SIGNED MESSAGE-----
>> Hash: SHA1
>>
>>
>> On Jan 23, 2009, at 9:09 PM, Tom Cloyd 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.
>>
>>> 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
>>>
>>
>> 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 Gilcher
>>
>> smtp: flo@andersground.net
>> jabber: Skade@jabber.ccc.de
>> gpg: 533148E2
>>
>> -----BEGIN PGP SIGNATURE-----
>> Version: GnuPG v1.4.8 (Darwin)
>>
>> iEYEARECAAYFAkl6L9sACgkQyLKU2FMxSOJU6ACfZQlLGOXbY8Rq3ChHRfpOWWBy
>> c5EAoJ9dVgjh4EagntgbEyr8Z1DGn8kq
>> =46uW
>> -----END PGP SIGNATURE-----
>>
>>
> 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?

[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.r...
Coming in 2009: The Well-Grounded Rubyist (http://manning....)

http://www.wis... => Independent, social wishlist management!

Tom Cloyd

1/23/2009 10:34:00 PM

0

David A. Black wrote:
> Hi Tom --
>
> On Sat, 24 Jan 2009, Tom Cloyd wrote:
>
>> Florian Gilcher wrote:
>>> -----BEGIN PGP SIGNED MESSAGE-----
>>> Hash: SHA1
>>>
>>>
>>> On Jan 23, 2009, at 9:09 PM, Tom Cloyd 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.
>>>
>>>> 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
>>>>
>>>
>>> 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 Gilcher
>>>
>>> smtp: flo@andersground.net
>>> jabber: Skade@jabber.ccc.de
>>> gpg: 533148E2
>>>
>>> -----BEGIN PGP SIGNATURE-----
>>> Version: GnuPG v1.4.8 (Darwin)
>>>
>>> iEYEARECAAYFAkl6L9sACgkQyLKU2FMxSOJU6ACfZQlLGOXbY8Rq3ChHRfpOWWBy
>>> c5EAoJ9dVgjh4EagntgbEyr8Z1DGn8kq
>>> =46uW
>>> -----END PGP SIGNATURE-----
>>>
>>>
>> 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?
>
> [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
>
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 Thomas'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.conf...

Thanks to Robert Dober 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.c...

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 Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< tc@tomcloyd.com >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Rob Biedenharn

1/23/2009 10:38:00 PM

0

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 Cloyd wrote:

> 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


# 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 Biedenharn http://agileconsult...
Rob@AgileConsultingLLC.com

David A. Black

1/23/2009 10:43:00 PM

0

Hi --

On Sat, 24 Jan 2009, Tom Cloyd wrote:

> 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 Thomas'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.conf...
>
> Thanks to Robert Dober 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.c...
>
> 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?

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.r...
Coming in 2009: The Well-Grounded Rubyist (http://manning....)

http://www.wis... => Independent, social wishlist management!

Tom Cloyd

1/23/2009 11:01:00 PM

0

Rob Biedenharn wrote:
> 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 Cloyd wrote:
>
>> 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
>
>
> # 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 Biedenharn http://agileconsult...
> Rob@AgileConsultingLLC.com
>
>
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 Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< tc@tomcloyd.com >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~