模块方法 returns NoMethodError

Module method returns NoMethodError

我正在尝试在我的模块中创建一个方法,该方法 returns 具有给定参数的散列。

module MyModule

  def self.my_method(*search_params)
    # do something...

    end
    self
  end
end

我看到很多类似的问题,问题是因为我正在定义一个实例方法,但我在定义中调用了 self 并继续收到错误,让我相信它可能是别的。

@example = { :name => 'John', :quote => 'Great fun!', :rank => 5 }
@example.my_method(:name => 'John') 

NoMethodError: undefined method `my_method` (NoMethodError)

我们无法理解你的方法试图做什么,因为逻辑没有意义,但这是你如何将你的方法添加到哈希 class。

module MyModule
  def my_method(*search_params)
    puts "search params: #{search_params}"
  end
end


class Hash
  include MyModule
end

@example = { :name => 'John', :quote => 'Great fun!', :rank => 5 }
@example.my_method(:name => 'John')

#=>search params: [{:name=>"John"}]

然而,这被称为 "monkey patching",这是不推荐的。使用继承可能会更好

module MyModule
  def monkey(*search_params)
    puts "search params: #{search_params}"
  end
end


class MonkeyHash < Hash
  include MyModule
end

@example = MonkeyHash.new(:name => 'John', :quote => 'Great fun!', :rank => 5)
@example.monkey(:name => 'John')

@example = { :name => 'John', :quote => 'Great fun!', :rank => 5 }

begin
  @example.monkey(:name => 'John')
rescue NoMethodError => e
  puts "Calling @exmaple.my_method raiesed: "
  puts e
  puts "@example is an instance of #{@example.class}. You may want to use MonkeyHash"
  puts "which includes the instance method 'monkey'"
end

或者你可以定义一个单例方法

puts "let's try it with a singleton method\n\n"

@singleton_example = { :name => 'John', :quote => 'Great fun!', :rank => 5 }

@singleton_example.define_singleton_method(:monkey) do |*search_params|
  puts "search params: #{search_params}"
end

puts "now @example has the monkey method see: \n"
@singleton_example.monkey(:name => 'John')
puts "@singleton_example is still an instance of #{@singleton_example.class}"

@example 是哈希的实例,而模块根本不包含在哈希 class 中。您需要先将其添加到哈希 class。

class Hash
  include MyModule
end

我建议您阅读 Ruby classes 和模块的基础知识。