【发布时间】:2018-06-15 05:56:22
【问题描述】:
我正在试验 Enumerable 和 Comparable。我阅读了文档并想尝试一下。
class Apple
attr_accessor :color
end
class Fruit
include Enumerable
include Comparable
attr_accessor :apples
def initialize
@apples = []
end
def <=> o
@apple.color <=> o.color
end
def each
@apples.each {|apple| yield apple }
end
def to_s
"apple: #{@apple.color}"
end
end
fruit = Fruit.new
a1 = Apple.new
a1.color = :red
a2 = Apple.new
a2.color = :green
a3 = Apple.new
a3.color = :yellow
fruit.apples.push a1
fruit.apples.push a2
fruit.apples.push a3
有两件事没有按预期工作。所以我重写了to_s,我希望数组的每个索引都包含一个像“apple:red”这样的字符串。相反,我得到了这个:
fruit.sort
=> [#<Apple:0x007fbf53971048 @apples=[], @color=:green>, #<Apple:0x007fbf53999890 @apples=[], @color=:red>, #<Apple:0x007fbf5409b530 @apples=[], @color=:yellow>]
第二个问题是当我包含 Enumerable 时,Enumerable 的实例方法应该在继承类之前添加到祖先链中。这应该包括 Enumerable 的方法,如 with_each、reduce 等到祖先链。但是,当我这样做时:
fruit.each.with_index(1).reduce({}) do |acc,(apple,i)|
acc << { i => apple.color}
end
LocalJumpError: no block given (yield)
如您所见,我收到了 LocalJumpError。我期望得到这样的结果:
{ 1 => :red, 2 => :green, 3 => :yellow}
我做错了什么?我按照我应该定义的方式定义了each,但它没有按预期工作。
【问题讨论】:
-
您的命名约定有点奇怪。大多数人会认为苹果是一种水果。有一个可以包含苹果的水果是很令人困惑的。
标签: ruby