我想了解Ruby Koans的一些内容。在一个教训,我们做两个类,如下所示:红宝石Koans和字符串
class CanNotBeTreatedAsString
def to_s
"non-string-like"
end
end
not_like_a_string = CanNotBeTreatedAsString.new
not_like_a_string == "non-string-like"
class CanBeTreatedAsString
def to_s
"string-like"
end
def to_str
to_s
end
end
like_a_string = CanBeTreatedAsString.new
like_a_string.to_str == "string-like"
def acts_like_a_string?(string)
string = string.to_str if string.respond_to?(:to_str)
string.is_a?(String)
end
assert_equal false, acts_like_a_string?(CanNotBeTreatedAsString.new)
assert_equal true, acts_like_a_string?(CanBeTreatedAsString.new)
所以两个阶级,最后两个“断言”语句是什么我并不清楚。这两个类别几乎完全相同,除了第二个类别只有另一个功能to_str
,可拨打to_s
。我不明白为什么第二个assert语句是真的(因此第二个类可以被视为一个字符串),只是因为有第二个函数调用第一个函数。
我注意到问题的关键是'acts_like_a_string?'的定义方式。我在irb中稍微更改了代码,因此它会响应':to_s'。 –