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?
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
I think the definition needs to be:
def Test.test
puts "test"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With