Ruby on rails #<;的代码重构未定义方法;阵列:0x00559ec6b7d918>;H

Ruby on rails #<;的代码重构未定义方法;阵列:0x00559ec6b7d918>;H,ruby-on-rails,function,refactoring,Ruby On Rails,Function,Refactoring,我试图通过在我的应用程序中创建方法来重新考虑我的代码。例如,我有以下几点: @clean_doc = @doc_broken_down_by_lines.reject { |a| a.split.size < 6 } 但是我得到了错误 undefined method `remove_lines_with_less_than_6_words' for #<Array:0x00559ec6b7d918> 未定义的方法“删除小于6个单词的行”# 我应该把代码放在哪里?为什么我

我试图通过在我的应用程序中创建方法来重新考虑我的代码。例如,我有以下几点:

@clean_doc = @doc_broken_down_by_lines.reject { |a| a.split.size < 6 }
但是我得到了错误

undefined method `remove_lines_with_less_than_6_words' for #<Array:0x00559ec6b7d918>
未定义的方法“删除小于6个单词的行”#
我应该把代码放在哪里?为什么我会得到错误,而代码看起来是一样的?谢谢

我应该把代码放在哪里

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

def remove_lines_with_less_than_6_words(arr)
  arr.reject { |a| a.split.size < 6 }
end
但是,您可以在控制器中添加该方法(私有方法),并使用
@doc\u breaked\u down\u by\u line
,而无需将其作为参数传递(因为作为实例变量,它将在类中的所有实例方法中可用):

为什么我会得到错误,而代码看起来是一样的

它看起来一模一样,但根本不一样。使用Ruby,您可以使用
调用实例方法,因此,由于
reject
Array
类中的一个实例方法,因此可以使用
my_Array.reject
调用它

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

因此,执行my_array.my_custom_method将导致出现以下错误:

未定义的方法“我的自定义方法”

@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>
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)
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