Ruby Koans: Where are the quotes in this return value?

柔情痞子 提交于 2019-12-08 14:48:48

问题


I'm working on the following Ruby Koan:

class Dog7
  attr_reader :name

  def initialize(initial_name)
    @name = initial_name
  end

  def get_self
    self
  end

  def to_s
    __
  end

  def inspect
    "<Dog named '#{name}'>"
  end
end

def test_inside_a_method_self_refers_to_the_containing_object
  fido = Dog7.new("Fido")

  fidos_self = fido.get_self
  assert_equal "<Dog named 'Fido'>", fidos_self
end

def test_to_s_provides_a_string_version_of_the_object
  fido = Dog7.new("Fido")
  assert_equal __, fido.to_s
end

The first half of the first assert_equal is what I am trying to fill in. This code gives the error:

<"<Dog named 'Fido'>"> expected but was  <<Dog named 'Fido'>>.

The problem is, I'm stuck on how to match the return value. It looks to me like a string literal return value, but I don't know how to express that without using quote marks, and/or backslashes. Nothing I try seems to work.

Help?


回答1:


After staring at it for a while, again, I figured out where they were going with the lesson. Changing the first assert to "assert_equal fido, fidos_self" made the test pass. I was thrown by the error giving the same output as the inspect method, sans quotes. Thanks for helping me work through it.




回答2:


Changing test_inside_a_method_self_refers_to_the_containing_object to following works:

def test_inside_a_method_self_refers_to_the_containing_object
  fido = Dog7.new("Fido")

  fidos_self = fido.get_self
  assert_equal "<Dog named 'Fido'>", fidos_self.inspect # .inspect added.
end


Ok, were there more gaps to fill? I have an answer, but it seems you already filled a gap incorrectly.




回答3:


The error is a type object error; the first element is a string type and the second is a Dog7 type. The solution is to match the types appropriately.

Check the return values of:

fidos_self.is_a?(String)
fidos_self.is_a?(Dog7)
fidos.is_a?(Dog7)
fidos_self
fidos


来源:https://stackoverflow.com/questions/8226588/ruby-koans-where-are-the-quotes-in-this-return-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!