我正在尝试在我的模块中创建一个方法,该方法返回具有给定参数的哈希值。
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)
我们无法理解你的方法试图做什么,因为逻辑没有意义,但这里是你如何将你的方法添加到 Hash 类。
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"}]
然而,这被称为“猴子补丁”,不推荐使用。使用继承可能会更好
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}"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句