The simpelest of module function scoping...

T

Tom Verbeure

It's a little sad that I've written many lines of ruby code, but I
can't something as simple as this to work:

#! /usr/bin/env ruby
module T

def t(x)
puts x
end

T::t(5)
end

../t.rb:8: undefined method `t' for T:Module (NoMethodError)

Obviously, I've tried different incantations, like t(5), T.t(5) etc.
No sigar... I must be missing something really trivial...

Tom
 
T

Tom

As happens so many times, a few tries later, I figured out that I need
to do this:

....
def T::t(x)
....

And then all works fine.

Which leads to the follow: why was the language designed this way? It
all seems a bit redundant.

And if I still keep the original def t(x), how can it be used?

Thanks,
Tom
 
J

Joel VanderWerf

Tom said:
It's a little sad that I've written many lines of ruby code, but I
can't something as simple as this to work:

#! /usr/bin/env ruby
module T

def t(x)

def T.t(x)
or
def self.t(x)

or wrap in class << self...end, or see ri module_function.
 
J

Joel VanderWerf

Tom said:
And if I still keep the original def t(x), how can it be used?

You can "mix" it into a class:

class C
include T
def foo; t(...); end
end
 
T

Tom

... or see ri module_function.

Interesting. I had no idea this existed. I think I'll need to remove
the big layer of dust from my 'Ruby for Rails' book and restudy these
things again.

Tom
 
M

Matt Neuburg

Tom said:
As happens so many times, a few tries later, I figured out that I need
to do this:

...
def T::t(x)
...

And then all works fine.

Which leads to the follow: why was the language designed this way? It
all seems a bit redundant.

Actually it's extraordinary simple and beautiful. Read my Ruby intro:

http://www.apeth.com/rubyIntro/justenoughruby.html

Read fairly quickly (since you probably know it all, already) just up to
section 1.13 ("The truth? You couldn't handle the truth!"). You will at
that point suddenly understand this syntax and why it is needed. m.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,938
Members
47,473
Latest member
pioneertraining

Latest Threads

Top