创建任意字符层次结构

时间:2012-07-23 13:19:42

标签: ruby string compare

假设我有4个字符,A,P,B,N。我希望能够比较它们:

A> P> B> N>甲

如何在Ruby中实现这一目标?

4 个答案:

答案 0 :(得分:2)

根据您的评论,您似乎尝试将这些元素放入订单,而是在某些之间定义一些二元关系他们可以通过多种方式在Ruby中执行此操作,具体取决于您以后打算如何使用该关系。

最简单的方法就是定义有序的相关元素对:

MAP = [
  ['A', 'P'],
  ['P', 'B'],
  ['B', 'N'],
  ['N', 'A']
]

然后在需要“比较”两个元素时使用它。

def beats? one, other
  MAP.member?([one, other])
end

beats? 'A', 'B'
# => false 
beats? 'A', 'P'
# => true 
beats? 'N', 'A'
# => true 

PS。您可以使用类似

的字符串从字符串生成地图
MAP = 'APBNA'.chars.each_cons(2).to_a

答案 1 :(得分:1)

其中一种可能的解决方案是创建一个类,例如characterweight等。并在其中实现<=>运算符(方法)。

不要忘记在此课程中加入Comparable mixin。

class ComparableCharacter
  include Comparable
  attr_accessor :character, :weight

  def <=>(another)
    weight <=> another.weight
  end
end

答案 2 :(得分:0)

a = "APBN"
h = {};(0...a.size).each{|i| h[a[i].chr] = i}
b = ['A','P','A','N', 'B','P']
b.sort_by{|t| h[t] }

当然,这不适用于你的例子,因为你的订单不好 - 你永远不会有A&gt; P>答,但至少它会告诉你如何根据你想要的顺序进行排序。

答案 3 :(得分:0)

如果有人感兴趣,这是我的建议(三元比较 - 因为比较不是二元操作!!! ):

class RockPaperScissors

  ITEMS = %W(A P B N)

  def self.compare(item, other_item)
    new(item).compare other_item
  end


  def initialize(item)

    # input validations?

    @item = item
  end

  def compare(other_item)

    # input validations?

    indexes_subtraction = ITEMS.index(@item) - ITEMS.index(other_item)

    case indexes_subtraction
    when 1, -1
      - indexes_subtraction
    else
      indexes_subtraction <=> 0
    end

  end

end

require 'test/unit'
include MiniTest::Assertions

assert_equal RockPaperScissors.compare('A', 'A'), 0
assert_equal RockPaperScissors.compare('P', 'P'), 0
assert_equal RockPaperScissors.compare('B', 'B'), 0
assert_equal RockPaperScissors.compare('N', 'N'), 0
assert_equal RockPaperScissors.compare('A', 'P'), 1
assert_equal RockPaperScissors.compare('P', 'A'), -1
assert_equal RockPaperScissors.compare('P', 'B'), 1
assert_equal RockPaperScissors.compare('B', 'P'), -1
assert_equal RockPaperScissors.compare('B', 'N'), 1
assert_equal RockPaperScissors.compare('N', 'B'), -1
assert_equal RockPaperScissors.compare('N', 'A'), 1
assert_equal RockPaperScissors.compare('A', 'N'), -1

说明

平等:(A,A)比较

  1. 索引:iA:0; iA:0
  2. iA - iA = 0
  3. A等于A,所以我们可以返回0
  4. 多数:(A,P)

    1. 索引:iA:0; iP:1
    2. iA - iP = -1
    3. A&gt; P,所以我们必须获得1;我们可以使用-函数:- (-1) -> 1
    4. 少数民族:(P,A)

      1. 索引:iP:1; iA:0
      2. iP - iA = 1
      3. P&lt; A,所以我们必须获得-1;我们可以使用-函数:- (1) -> -1
      4. 边缘情况1:(N,A)

        1. 索引:iN:3,iA:0
        2. iN - iA = 3
        3. N&gt; A,所以我们必须获得1;我们可以使用<=>函数:(3 <=> 0) -> 1
        4. 边缘情况2:(A,N)

          1. 索引:iA:0,iN:3
          2. iA - iN = -3
          3. A&lt; N,所以我们必须获得-1;我们可以使用<=>函数:(3 <=> 0) -> 1
          4. 其余的是重构:0可以使用0函数转换为<=>