Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby script execution within a module

Tags:

ruby

Why is is that the following fails?

module Test
    def test
        puts "test"
    end

    puts "testing"
    test
end

I get this output:

testing
test.rb:6:in `test': wrong number of arguments (ArgumentError)
    from test.rb:6:in `<module:Test>'
    from test.rb:1:in `<main>'

Is it because the module hasn't been "compiled" yet, since the end keyword hasn't been reached?

like image 429
decitrig Avatar asked Jul 05 '26 06:07

decitrig


2 Answers

Using a previously unused name might clear up your confusion:

module Test
  def my_test
    puts "my_test"
  end
  puts "testing"
  my_test
end

results in

testing
NameError: undefined local variable or method `my_test' for Test:Module

Inside the module...end block, when you invoke my_test, what is self (the implicit receiver)? It is the module Test. And there is no my_test "module method". The my_test method defined above is like an instance method, to be sent to some object that includes this module.

You need to define my_test as a "module method":

module Test
  def self.my_test
    puts "my_test"
  end
  puts "testing"
  my_test
end

results in

testing
my_test

If you want my_test as an instance method and you want to invoke it inside your module definition:

method Test
  puts "testing"
  Object.new.extend(self).my_test
end

gives

testing
my_test
like image 102
glenn jackman Avatar answered Jul 09 '26 02:07

glenn jackman


I think the definition needs to be:

def Test.test
    puts "test"
end
like image 32
Mark Wilkins Avatar answered Jul 09 '26 01:07

Mark Wilkins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!