我正在尝试通过在我的应用程序中创建方法来重构我的代码。例如,我有以下内容:
@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,您可以使用.
调用实例方法,因此由于reject
是Array
类中的实例方法,您可以可以使用 my_array.reject
调用它。
但是一旦您创建了自己的方法,它就不会在 Array 类中定义,因此它不能作为 Array 中的实例方法使用,它是一个实例定义该方法的类的方法(例如 MyController
或 MyModel
或您决定定义该方法的任何位置)。
这样做 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/