开发者

Can't call ruby module method

开发者 https://www.devze.com 2023-03-22 12:18 出处:网络
cat modu开发者_运维知识库le1.rb => module Module1 def add(a,b) return a+b end def subtract(a,b) return a-b

cat modu开发者_运维知识库le1.rb =>

module Module1

    def add(a,b)
        return a+b
    end

    def subtract(a,b)
        return a-b
    end

end

cat call.rb =>

#!/home/user1/.rvm/rubies/ruby-1.9.2-p180/bin/ruby

include './Module1.rb

temp = add(5,2)
print temp
print "\n"

ruby call.rb =>

<internal:lib/rubygems/custom_require>:29:in `require': no such file to load -- Module1 (LoadError)
    from <internal:lib/rubygems/custom_require>:29:in `require'
    from call.rb:3:in `<main>'

Can anyone fix it ?


Place two files in the same directory. Call the first one module1.rb and make it look exactly like this:

module Module1
  def add(a, b)
    return a + b
  end
  def subtract(a, b)
    return a - b
  end
end

Call the second one call.rb and make it look exactly like this

require './module1.rb'
include Module1

temp = add(5,2)
print temp
print "\n"

At the commandline, run ruby call.rb. You should see an output of 7.


I assume you're using Ruby 1.9?

Then try

require_relative 'module1'
include Module1

temp = add(5,2)
puts temp

That should do it.


require loads a file from Ruby's $LOAD_PATH. If you want to load a file relative to the current file, then you need to use require_relative instead.


You should require the file before including.

require 'module1.rb'
include Module1

And make sure the two file are in same directory.

0

精彩评论

暂无评论...
验证码 换一张
取 消