ruby-on-rails - 在 ruby​​ 中创建一个函数

标签 ruby-on-rails ruby function

我在为我的 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)

那样 StringInteger类获取 YourModule 中定义的所有方法.

有关更深入的信息,请阅读这篇文章:Why Ruby’s Mixins Gives Rails an Advantage over Java Frameworks

关于ruby-on-rails - 在 ruby​​ 中创建一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2675777/

相关文章:

ruby-on-rails - Ruby 删除哈希数组中的重复条目,但基于多个值

ruby-on-rails - 使用 simple_form Bootstrap 输入组包装器

ruby - 在 RSpec 中期待 Lambda

java - 处理(Java): How to make a plotted sine function look continuous instead of separate dots when the amplitude of the function increases

ruby-on-rails - 将变量从 View 传递到 View 外的模型

ruby-on-rails - 更改友好 ID 默认列

ruby - 无法使用 gsub 和 hash 修改卡住的字符串错误

html - 如何单击 watir 中的按钮元素?

python - 开发启发式方法来测试简单的匿名 Python 函数的等效性

javascript - 函数式编程实践