The simpelest of module function scoping

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

./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

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

Tom wrote:

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

… 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

Tom Verbeure wrote:

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.

Tom [email protected] wrote:

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs