我正在Ruby Koans about_to_str.rb工作。我已经开始工作,但有些代码我不明白。我很困惑为什么CanNotBeTreatedAsString
类to_s
产生的结果与CanBeTreatedAsString
to_s
两项测试test_to_str_allows_objects_to_be_treated_as_strings
& test_normally_objects_cannot_be_used_where_strings_are_expected
通过执行同样的操作来检查存在的文件,但是一个文件会引发错误而另一个文件没有。
有人可以提供我不知道的概念的高级概述吗?
class CanNotBeTreatedAsString
def to_s
"non-string-like"
end
end
def test_to_s_returns_a_string_representation
not_like_a_string = CanNotBeTreatedAsString.new
assert_equal "non-string-like", not_like_a_string.to_s
end
def test_normally_objects_cannot_be_used_where_strings_are_expected
assert_raise(TypeError) do
File.exist?(CanNotBeTreatedAsString.new)
end
end
class CanBeTreatedAsString
def to_s
"string-like"
end
def to_str
to_s
end
end
def test_to_str_also_returns_a_string_representation
like_a_string = CanBeTreatedAsString.new
assert_equal "string-like", like_a_string.to_str
end
def test_to_str_allows_objects_to_be_treated_as_strings
assert_equal false, File.exist?(CanBeTreatedAsString.new)
end