ruby-on-rails - 代码重构 #<Array :0x00559ec6b7d918>h 的未定义方法

标签 ruby-on-rails function refactoring

我正在尝试通过在我的应用程序中创建方法来重构我的代码。例如,我有以下内容:

@clean_doc = @doc_broken_down_by_lines.reject { |a| a.split.size < 6 }

我想把

.reject { |a| a.split.size < 6 }

在一个单独的函数中

我试图把

def remove_lines_with_less_than_6_words
  self.break_into_lines.reject { |a| a.split.size < 6 }
end

在许多不同的位置,包括在同一 Controller 中或在事件记录模型中并放置

@clean_doc = @doc_broken_down_by_lines.remove_lines_with_less_than_6_words

但我收到错误

undefined method `remove_lines_with_less_than_6_words' for #<Array:0x00559ec6b7d918>

我应该把代码放在哪里?为什么我会收到错误,而代码看起来相同?谢谢。

最佳答案

Where should I put the code?

您需要将数组作为参数传递给该方法,而不是将其用作Array的实例方法:

def remove_lines_with_less_than_6_words(arr)
  arr.reject { |a| a.split.size < 6 }
end

并像这样使用它:

@clean_doc = remove_lines_with_less_than_6_words(@doc_broken_down_by_lines)

但是,您可以在 Controller 中添加该方法(私有(private)方法)并使用 @doc_broken_down_by_lines 而无需将其作为参数传递(因为作为实例变量,它将在所有实例方法中可用)类):

private
def remove_lines_with_less_than_6_words
  @doc_broken_down_by_lines.reject { |a| a.split.size < 6 }
end

并像这样使用它:

@clean_doc = remove_lines_with_less_than_6_words

Why do I get the error whereas the code appears identical?

看起来相同,但其实根本不一样。使用Ruby,您可以使用.调用实例方法,因此由于rejectArray类中的实例方法,您可以可以使用 my_array.reject 调用它。

但是一旦您创建了自己的方法,它就不会在 Array 类中定义,因此它不能作为 Array 中的实例方法使用,它是一个实例定义该方法的类的方法(例如 MyControllerMyModel 或您决定定义该方法的任何位置)。

这样做 my_array.my_custom_method 将导致您收到错误:

Undefined method `my_custom_method' for <#Array:...>

关于ruby-on-rails - 代码重构 #<Array :0x00559ec6b7d918>h 的未定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619986/

相关文章:

ruby-on-rails - 更新到 Rails 3.1.10 时出现冲突

c - 如何在一个函数中使用指向同一结构的两个参数?

C: "if((a+=b) > c)"是如何工作的?

C# Xamarin 避免代码重复

ruby-on-rails - RoR - 为什么这个 ID 不起作用?

jquery - Rails 中的 Fancybox 表单无法正常工作

function - 缺少函数体

java - 在 IntelliJ 或 Android Studio 中重构时如何将静态变量从一个类移动到另一个类?

ruby-on-rails - 致命 : role "root" does not exist

c - Linux 中的 setprogname