[#1816] Ruby 1.5.3 under Tru64 (Alpha)? — Clemens Hintze <clemens.hintze@...>

Hi all,

17 messages 2000/03/14

[#1989] English Ruby/Gtk Tutorial? — schneik@...

18 messages 2000/03/17

[#2241] setter() for local variables — ts <decoux@...>

18 messages 2000/03/29

[ruby-talk:01857] Re: Another question from a newbie

From: Dave Thomas <Dave@...>
Date: 2000-03-15 19:36:03 UTC
List: ruby-talk #1857
"David Douthitt" <DDouthitt@cuna.com> writes:

> Why does this snippet fail?
> 
>       class String
>          def String.comment (str)
>             str =~ /^(#| *$)/
>          end
>       end

This defines a class method (also called by Ruby a singleton
method). These methods are invoked without an object instance.

>       File.open(ENV["ORACONF"]) { |conf|
>          conf.readlines.each { |line|
>             next if line.comment

But here you're calling the method 'comment' on a String object. As
there is no instance method called 'comment', you'll get the failure.

> However, if the last line is converted to:
> 
>             next if String.comment(line)

This works because you're calling the class method.

If you wanted to do this using an instance method, you'd code
something like

       class String
          def comment?
             self =~ /^(#| *$)/
          end
       end

       ...

       next if line.comment?


By the way, there's another fun Ruby trick for doing this kind of
thing. You could code up a simple iterator which only returns
non-blank non-comment lines

   def nonCommentLines(aFile)
      aFile.each { |line|
        line.gsub!(/#.*/, '')
        yield(line) unless line =~ /^\s*$/
      }
   end

   File.open(ENV["ORACONF"]) { |conf|
      nonCommentLines(conf) {  |line|
        print line
      }
   }


Regards


Dave

In This Thread

Prev Next