我在为我的 Rails 应用程序创建函数时遇到了一些问题。
我希望它像这样工作:
str = "string here"
if str.within_range?(3..30)
puts "It's withing the range!"
end
为此,我将其添加到我的应用程序助手中:
def within_range?(range)
if self.is_a?(String)
(range).include?(self.size)
elsif self.is_a?(Integer)
(range).include?(self)
end
end
我收到此错误:
undefined method `within_range?' for "":String
有谁知道问题是什么?
最佳答案
您正在尝试的不仅仅是创建一个新功能。您正在尝试添加 新方法至String
.
为此,您可以将函数 within_range?
进入一个新模块,然后将该模块包含到您想要的类中。
通常这是通过调用 include
来完成的。方法,但由于您无法调用 String.include
或更改String
的源代码或 Integer
上课,你必须作弊并使用send
方法。
String.send(:include, YourModule)
Integer.send(:include, YourModule)
那样
String
和 Integer
类获取 YourModule
中定义的所有方法.有关更深入的信息,请阅读这篇文章:Why Ruby’s Mixins Gives Rails an Advantage over Java Frameworks
关于ruby-on-rails - 在 ruby 中创建一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2675777/