我尝试使用Integer(word)
irb
可以理解的=> 1234
,但是当iI编程num = word.to_s
或Integer(word).to_s
时,它仍会输出一个整数。
我看到测试中的差异,但输入无关紧要吗?
所有整数应该输出为字符串?
对于上下文,我正在尝试完成此练习......
http://ruby.learncodethehardway.org/book/ex48.html
class Lexicon
Pair = Struct.new(:token, :key)
def scan(stuff)
@words = stuff.split(" ")
return analyze
end
def analyze
hash = { "north" => :direction, "south" => :direction, "east" => :direction, "west" => :direction,
"go" => :verb, "stop" => :verb, "kill" => :verb, "eat" => :verb,
"the" => :stop, "in" => :stop, "of" => :stop, "from" => :stop, "at" => :stop, "it" => :stop,
"door" => :noun, "bear" => :noun, "princess" => :noun, "cabinet" => :noun}
@words.map do |word|
#hash.keys.include?(word) ? Pair.new(hash[word], word) : Pair.new(:error, word)
begin
Integer(word).to_s
#Integer(word)
#num = word.to_s
#Pair.new(:number, num)
Pair.new(:number, word)
rescue ArgumentError => x
if hash.keys.include?(word)
Pair.new(hash[word], word)
else
Pair.new(:error, word)
end
end
end
end
end
$ ruby test_lexicon.rb
Run options:
# Running tests:
[4/6] LexiconTests#test_numbers = 0.00 s
1) Failure:
test_numbers(LexiconTests) [test_lexicon.rb:49]:
<[#<struct Lexicon::Pair token=:number, key="1234">]> expected but was
<[#<struct Lexicon::Pair token=:number, key=1234>]>.
Finished tests in 0.004981s, 1204.5774 tests/s, 2208.3919 assertions/s.
6 tests, 11 assertions, 1 failures, 0 errors, 0 skips
ruby -v: ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
def test_numbers()
assert_equal(@@lexicon.scan("1234"), [Pair.new(:number, 1234)])
result = @@lexicon.scan("3 91234")
assert_equal(result, [Pair.new(:number, 3),
Pair.new(:number, 91234)])
end
答案 0 :(得分:0)
在这个块中:
Integer(word).to_s
Pair.new(:number, num)
您引用变量num
,该变量未在您粘贴的代码中声明。您似乎没有测试您认为自己正在测试的内容。
然而,失败:
<[#<struct Lexicon::Pair token=:number, key="1234">]> expected but was
<[#<struct Lexicon::Pair token=:number, key=1234>]>.
......具有误导性。 The test:
assert_equal(@@lexicon.scan("1234"), [Pair.new(:number, 1234)])
...正在寻找@@lexicon.scan("1234")
的结果[Pair.new(:number, 1234)]
。这就是assert_equal
的expected
和actual
参数被转置。
因此,当String("1234")
实际需要时,您将返回Integer(1234)
。
因此,简而言之,您的阻止必须是:
Pair.new(:number, Integer(word))
......你的测试都应该通过。