学习Ruby Hard Way ex。 48

我正在努力学习Ruby,并且通过Zed Shaw的大部分学习Ruby Ruby the Hard Way,但是这个最新的练习让我完全难过。 这是一种反向练习,让你创建一个可以通过提供的代码进行测试的类Lexicon。

您应该创建Lexicon,以便它可以通过用户输入并从中获取各种数据。 到目前为止我所有的测试方向输入,例如:

class Lexicon Pair = Struct.new(:qualifier, :value) userinput = gets.chomp() userwords = userinput.split() for i in userwords if userwords[i].include?("north", "south", "east", "west") directions = Pair.new("direction", userwords[i]) else i++ end end end 

相应的测试代码是:

 require 'test/unit' require_relative "../lib/lexicon" class LexiconTests < Test::Unit::TestCase Pair = Lexicon::Pair @@lexicon = Lexicon.new() def test_directions() assert_equal([Pair.new(:direction, 'north')], @@lexicon.scan("north")) result = @@lexicon.scan("north south east") assert_equal(result, [Pair.new(:direction, 'north'), Pair.new(:direction, 'south'), Pair.new(:direction, 'east')]) end 

提前感谢大家的帮助。 我知道我可能已经离开了,但我正在努力学习Ruby the Hard Way!

您应该在扫描方法中包装for循环,因为这是测试用例所期望的。 扫描方法还需要返回“对”列表。

尝试这样的事情。

 def scan(userwords) sentence = Array.new userwords.each { |word| if word.include?("north", "south", "east", "west") sentence.push(Pair.new(:direction, word)) } sentence end 

这应该有助于您开始朝着正确的方向前进。