尝试将哈希输出到字符串

时间:2015-08-09 20:10:03

标签: ruby

如果我手动输入这样的参数,我可以运行代码:

class String
  define_method(:word_count) do |string_of_text_to_search|
    frequencies = Hash.new(0)
    array_of_search_string = string_of_text_to_search.split(' ')
    array_split_self = self.split(" ")
    array_of_search_string.each() do |word|
      if array_split_self.include?(word) then frequencies[word] += 1 end
    end
    if frequencies.empty?
      "No matches."
    else
      frequencies.each() { |word, count| print word + ": " + count.to_s + " " }
    end
  end
end

"car bed".word_count("car door bed car car if and but bed")
#=> car: 3 bed: 2 => {"car"=>3, "bed"=>2}

这是我的rspec文件:

require('rspec')
require('word_count')
require('pry')

describe('String#word_count') do
  it("takes user input to search for word in a string. If it finds a word return the count of the word in string form") do
    expect(("puppy").word_count("I have a dog named dog")).to(eq("No matches."))
  end
  it("takes argument from method and searches for word count within that argument") do
    expect(("cat dog").word_count("I have a dog named dog")).to(eq("dog: 2 "))
  end
  it("it takes mutliple search words") do
    expect(("dog cat").word_count("I have cat named bob and a dog named dog")).to(eq("dog 2 cat 1 "))
  end
end

Rspec失败并告诉:

.dog: 2 Fcat: 1 dog: 2 F

Failures:

  1) String#word_count takes argument from method and searches for word count within that argument
     Failure/Error: expect(("cat dog").word_count("I have a dog named dog")).to(eq("dog: 2 "))

       expected: "dog: 2 "
            got: {"dog"=>2}

       (compared using ==)

       Diff:
       @@ -1,2 +1,2 @@
       -"dog: 2 "
       +"dog" => 2,

     # ./spec/word_count_spec.rb:10:in `block (2 levels) in <top (required)>'

  2) String#word_count it takes mutliple search words
     Failure/Error: expect(("dog cat").word_count("I have cat named bob and a dog named dog")).to(eq("dog 2 cat 1 "))

       expected: "dog 2 cat 1 "
            got: {"cat"=>1, "dog"=>2}

       (compared using ==)

       Diff:
       @@ -1,2 +1,3 @@
       -"dog 2 cat 1 "
       +"cat" => 1,
       +"dog" => 2,

     # ./spec/word_count_spec.rb:13:in `block (2 levels) in <top (required)>'

Finished in 0.01116 seconds (files took 0.18346 seconds to load)

也许有人可以关心比我更多的知识可以给我一个体面的解释。

1 个答案:

答案 0 :(得分:1)

问题在于您的实施代码。在Ruby中,返回的值(来自方法)是对最后一个语句的评估(如果不是代码中前面使用的return)。

您假设将返回一个值(但实际上只是呈现字符串)是行:

frequencies.each() { |word, count| print word + ": " + count.to_s + " " }

如上所述,通过使用print,它会呈现字符串(在您的情况下为word + ": " + count.to_s + " "),而不是按预期返回准备好的字符串。

尝试将代码更改为:

frequencies.map { |word, count| word + ": " + count.to_s }
           .join(" ")

或者,为了保持稍微更多的Ruby方式

frequencies.map { |word, count| "#{word}: #{count}" }
           .join(" ")

请注意,这不会在字符串的末尾添加额外的空格

希望有所帮助!