开发者

Why am I getting NoMethodError from IRB for my own Module and method

I have taken this example exactly from the Ruby Cookbook. Unfortunately for me, like a whole lot of the examples in that book, this one does not work:

my file (Find.rb - saved both locally and to Ruby\bin):

require 'find'

    module Find
     def match(*paths)
      matched=[]
      find(*paths) { |path| matched << path if yield path }
      return matched
     end
     module_function :开发者_如何学Gomatch
    end

I try to call it this way from IRB, according to the example the book provides:

irb(main):002:0> require 'Find'
=> false

irb(main):003:0> Find.match("./") { |p| ext = p[-4...p.size]; ext && ext.downcase == "mp3" }

It SHOULD return a list of mp3 files in my recursive directory. Instead, it does this:

NoMethodError: undefined method `match' for Find:Module
        from (irb):3
        from C:/Ruby192/bin/irb:12:in `<main>'

What gives? I'm new at this (although I MUST say that I'm farther along with Python, and much better at it!).

How can I get IRB to use my method?


I ran into this with irb on a Mac running Snow Leopard while using the default version of ruby (and irb of course) installed with OS X. I was able to get past it by including the module in IRB after loading the module or in the file after the module definition.

include module_name

I'm not sure if this is a defect or known behavior.


The only explanation is that the code you posted is not the code you are running, since both carefully reading it and simply cut&paste&running it shows absolutely no problems whatsoever.


What directory are you calling IRB from? Try calling it from the directory where your find.rb file is located. Also, I don't know if it makes any difference but convention is to name the file the lowercase version of the module / class. So the module would be Find and the file name would be find.rb. You shouldn't need the require call in the file itself.

So, start your command prompt window, cd into the directory that contains find.rb and run irb. In IRB you should be able to require "find" and it should return true. From there you should be able to call Find.match.


I know this question is already 3 years old, but since this is the first hit on google for the problem, and I had been banging my head against the wall all afternoon with the same problem doing the tutorial here: http://ruby.learncodethehardway.org/book/ex25.html, here goes: the function definition in the module should read

module Find
  def Find.match(*paths)
    ...
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜