2014-02-22 96 views
-2

第一个代码有效,但我不明白为什么第二个代码没有。任何洞察力将不胜感激。我知道在这个例子中我真的不需要一个数组,我只是想为了学习而努力。Array与模运算符不起作用

def stamps(input) 
    if input % 5 == 0 
    puts 'Zero!' 
    else 
    puts 'NO!' 
    end 
end 

print stamps(8) 

但这不工作:

array_of_numbers = [8] 

def stamps(input_array) 
    if input_array % 5 == 0 
    puts 'Zero!' 
    else 
    puts 'NO!' 
    end 
end 

print stamps(array_of_numbers) 
+2

没有为数组定义没有''%方法。你如何期待你的第二个例子工作? – toro2k

+1

那么,你期望第二个例子中的代码能做什么?如果阵列中同时存在8 *和* a 5,该怎么办?你期望你的代码做什么? – Ajedi32

+0

我为我的无知道歉,谢谢你们向我展示我的方式错误,我很感激! –

回答

0

因为input_array是一个数组,图8是一个数字。使用first来检索数组的第一个元素。

array_of_numbers = [8] 

def stamps(input_array) 
    if input_array.first % 5 == 0 
    puts 'Zero!' 
    else 
    puts 'NO!' 
    end 
end 

print stamps(array_of_numbers) 
0

下面的函数的情况下,工作原理是输入数字或数组:

def stamps(input) 
    input = [input] unless input.is_a?(Array) 
    if input.first % 5 == 0 
    puts 'Zero!' 
    else 
    puts 'NO!' 
    end 
end