在 Ruby 中根据数组中的索引比较项目
我有一个 Card 类,我想重载 >
运算符来与另一张牌进行比较(Ace 高于 King,King 高于 Queen,等等)。我已经忘记了我对 Ruby 知之甚少,也不知道从哪里开始。
class Card
@@RANKS = ['A', 'K', 'Q', 'J', 'T', '9', '8','7','6','5','4','3','2']
attr_reader :rank
def initialize(str)
@rank = str[0,1]
end
def > (other)
#?????
end
end
I have a Card
class and I want to overload the >
operator to compare against another card (Ace is higher than king, king higher than queen, etc). I've forgotten what little I ever knew about Ruby and don't have a clue where to start.
class Card
@@RANKS = ['A', 'K', 'Q', 'J', 'T', '9', '8','7','6','5','4','3','2']
attr_reader :rank
def initialize(str)
@rank = str[0,1]
end
def > (other)
#?????
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您定义飞船运算符而不是大于,您可能会更高兴。 (<=>)
例如,排序取决于它的定义。
http://ruby-doc.org/ruby-1.9/classes/Enumerable。 html
You might be happier if you define the spaceship operator instead of greater than. (<=>)
Sorting, for instance, depends on it being defined.
http://ruby-doc.org/ruby-1.9/classes/Enumerable.html
我同意达林特的观点。
您所需要做的就是包含 Comparable 并定义 <=>然后您就可以免费进行所有其他比较!为您提供比仅仅定义 '>' 更多的灵活性靠它自己。
用镐书里的话来说:
“Comparable mixin 可用于将比较运算符(<、<=、==、>= 和 >)以及 Between? 方法添加到类中。要实现此目的,Comparable假设任何使用它的类都定义了运算符<=>,因此,作为类编写者,您可以定义一个方法<=>,包括Comparable,并免费获得六个比较函数。”
(免费在线)镐书中提供了完整的示例:
http://ruby-doc.org/docs/ProgrammingRuby/html/ tut_modules.html#S2
(向下滚动几段到“Mixins 给你一种奇妙的控制方式......”)
I would agree with darrint.
All you need do is include Comparable and define <=> and then you will be able to do all the other comparisons for free! Giving you a lot more flexibility than just defining '>' on it's own.
In the words of the pickaxe book:
"The Comparable mixin can be used to add the comparison operators (<, <=, ==, >=, and >), as well as the method between?, to a class. For this to work, Comparable assumes that any class that uses it defines the operator <=>. So, as a class writer, you define the one method, <=>, include Comparable, and get six comparison functions for free."
A full example is available in the (free online) pickaxe book:
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html#S2
(scroll down a couple of paragraphs to 'Mixins give you a wonderfully controlled way..')
您可以使用
array.index
方法。以下代码检查两张卡的索引,如果other
卡出现在当前卡之后,则返回true
。You can use the
array.index
method. The following code checks the index of both cards and returnstrue
if theother
card appears after the current card.