1

所以这里有一个更 java-esq 的方法(我认为)......我在 Ruby 中有这段代码

class Human
  def move
    p 'Human move: X'
  end
end


class Computer
  def move
    p'Computer move: O'
  end
end

class Player
  def initialize(letter)
    if letter == 'X'
      return Human.new
    else
      return Computer.new
    end
  end
end

bob = Player.new('X')
bob.move

我期待回到 cli 'Human move: X' 我收到以下错误...

undefined method `move' for #<Player:0x007f8d930895a8> (NoMethodError)

任何人都可以帮助这个 Ruby 菜鸟吗?

- - - - - - - - - - - - -讨论 - - - - - - - - - - - -

现在我刚刚想出了一种方法,我猜想,使用继承和覆盖的“经典”Ruby 时尚。现在,这对我心中的子处理器毫无意义。我的意思是,如果我这样做......我可以只需要任何其他类文件中的类文件并实例化一个新对象。当您在 Java 中执行此操作时,它并没有真正的多态性......这是代码......

class Player
  def move
    return ""
  end
end

class Human < Player
  def move
    return 'Human move: X'
  end
end


class Computer < Player
  def move
    return'Computer move: O'
  end
end



players = [Human.new, Computer.new]
players.each {|player|
  print player.move
}
4

2 回答 2

6

You almost made it :) In ruby you can't return an arbitrary object from a constructor. Well, you can, but that return value is ignored. Instead use a Factory Method (in OOP speak).

class Human
  def move
    p 'Human move: X'
  end
end


class Computer
  def move
    p 'Computer move: O'
  end
end

class Player
  def self.get_player(letter)
    if letter == 'X'
      return Human.new
    else
      return Computer.new
    end
  end
end

bob = Player.get_player('X')
bob.move
# >> "Human move: X"
于 2012-11-02T18:46:47.913 回答
1

You're calling Player.new, so you'll get a Player object back, no matter what you return in the initialize function. If for some reason you don't want to instantiate Human and Computer directly, do something like that :

class Player
  def self.new_player(letter)
    if letter == 'X'
      return Human.new
    else
      return Computer.new
    end
  end
end

bob = Player.new_player('X')
bob.move #Prints your output
于 2012-11-02T18:46:25.167 回答