class Filter
def filterMethod(arr)
new_array1 = puts arr.select.each_with_index { |str, i| i.odd? }
yield
new_array2 = puts arr.select.each_with_index { |str, i| i.even? }
yield
new_array3 = puts arr.reject! {|x| x < '3'}
yield
new_array4 = puts arr.reject! {|x| x < '4'}
yield
end
end
puts "Enter a list of numbers"
list = Array.new
list = gets.chomp
F= Filter.new
F.filterMethod(list) {puts "--------"}
#list = Array.new
我无法在类中访问数组。如何在方法中获取数组值。它显示以下错误:
“`filterMethod':私有方法'select'调用nil:NilClass (NoMethodError)“
答案 0 :(得分:2)
让我们看看:
/include[@template]/*[@name][@value]
现在,
list = Array.new
# => [] # An Array
在list = gets.chomp
asd
# => "asd" # A String
F= Filter.new
F.filterMethod(list) # You are passing a String
Filter#filterMethod
因此:
NoMethodError:私有方法`select&#39;呼叫&#34; asd&#34;:String
您可以通过拆分将字符串转换为数组,方法是使用.chars
或.split
(都用于不同目的,读取文档)。这里:
# arr is supposed to be an Array
arr.select.each_with_index { |str, i| i.odd? } # list is passed as argument which is a String
或获取整数数组(因为您在方法中执行整数运算):
list = gets.chomp
12345
# => "12345" # A String
list = list.chars
# => ["1", "2", "3", "4", "5"] # An Array
答案 1 :(得分:0)
list = gets.chomp
返回一个字符串。你似乎期待一个阵列,所以需要额外的东西。例如:
list = gets.chomp.split
这仍然是str的列表,所以如果你想要注册,你可能需要另一个步骤
list = gets.chomp.split.map{|x|x.to_i}