【发布时间】:2014-05-13 23:17:08
【问题描述】:
短篇小说:
“为什么defined?(59[0][:whatever]) 评估为真?”
长篇大论:
我最近遇到了一些奇怪的行为,这让我很反感。
我正在开发一种对数据进行一些清洗的方法:
#Me washing input data:
def foo(data)
unless data && defined?(data[0]) && defined?(data[0][:some_param])
method2(data[0][:some_param])
else
freak_out()
end
end
我通常会编写测试,在其中吐出各种垃圾数据,以确保不会发生任何奇怪的事情:
describe "nice description" do
it "does not call method2 on junk data" do
expect(some_subject).to_not receive(:method2)
random_junk_data_array.each do |junk|
some_subject.foo(junk)
end
end
end
嗯,method2 是在这里调用的。它发生在 junk 是一个固定数字时。
我正在使用ruby 2.1.0,我可以看到Fixnum 有一个#[] 方法可以获取该位置的位,很好。
但是为什么fixnum[0][:some_param] 被认为是defined?
【问题讨论】: