【发布时间】:2013-03-31 20:09:57
【问题描述】:
http://rubymonk.com/learning/books/1/problems/148-array_of_fixnum
红宝石和尚建议:
def array_of_fixnums?(array)
array.all? { |x| x.is_a? Fixnum }
end
这很好,但是以下代码在 irb 1.9.2 中有效,但当 rubymonk 传递一个空数组时失败:
def array_of_fixnums?(array)
result = false
array.each { |n|
if n.is_a? Fixnum
result = true
else
result = false
end }
result
end
这里是 irb 输出:
1.9.2-p320 :001 > array_of_fixnums? []
=> false
以下是 rubymonk 对我的解决方案的评价:
returns 'true' for [1,2,3] ✔
returns 'false' for ['a',1,:b] ✔
returns 'true' for []
RSpec::Expectations::ExpectationNotMetError
expected false to be true
我想知道为什么会这样?
根据答案更新:
def array_of_fixnums?(array)
result = true
array.each { |n| return false unless n.is_a? Fixnum }
result
end
【问题讨论】:
标签: ruby