【发布时间】:2014-01-19 13:06:58
【问题描述】:
我正在尝试实现我的第一个 ruby 排序算法。这个算法基于一些特定的规则(“总是更喜欢 xxx 类型的对象而不是 yyy 类型的对象”),如果这些规则都没有触发,它使用 ruby -操作符。我在 ruby-on-rails 一对多关联上执行此操作。
问题是这个算法不返回数组本身,它只返回-1或1,比较的结果..但我实际上不明白为什么,因为我的结果只在排序块中返回.
这是我当前的代码:
def sort_products!
products.sort! do |p1, p2|
result = 0
# Scalable Products are always the last ones in order
if p1.class.name == "ScalableProduct"
result = -1
elsif p2.class.name == "ScalableProduct"
result = 1
end
if result == 0
# Put products producing electricity and heating down
if p1.can_deliver_electricity?
result = -1
elsif p2.can_deliver_electricity?
result = 1
end
end
# Else: Just compare names
result = p1.name <=> p2.name if result == 0
result
end
end
【问题讨论】:
-
你能显示调用该方法的代码吗?
-
请打印出 sort_products 中的 products 数组!调用排序之前的方法!方法。
标签: ruby-on-rails ruby arrays sorting