1

我不是说如何包含 ActiveRecord,但让我解释一下。

我想要一个Game带有一个difficultyLevelID和一个DifficultyLevel对象。

在 Rails 和 ActiveRecord(这是我熟悉的)中,这些将是表格,我将拥有has_manyandbelongs_to方法,然后我可以使用difficultyLevelID来获取东西,所以难度级别可能是Game.difficulty_level.name

如果我只是在做一个没有数据库的 Ruby 程序并且我想使用这种关系,即我想要Game一个ID难度级别和级别name本身在一个difficulties类中,我该怎么做(创建、维护和查询关系)只是用 Ruby,所以我可以说得到游戏难度级别的名称?

4

1 回答 1

0

20 小时内没有答案,所以我发布了自己的答案。

class Soduko
  attr_accessor :name, :rows, :columns, :difficulty_level
  def initialize // will probably move to parameters as defaults.
    @rows= 9
    @columns= 9
    @name= 'My Soduko'
    @difficulty_level= 'Medium'
  end

  def initial_number_count
    DifficultyLevel.start_with_numbers('Medium')
  end

end

class DifficultyLevel

  def self.start_with_numbers(difficulty_level)
    case difficulty_level
      when 'Easy'
      then 30
      when 'Medium'
      then 20
      when 'Hard'
      then 10
      else 20
    end

  end

end

当然还有测试:

require './soduko'

describe Soduko, '.new' do

  before { @soduko_board  = Soduko.new }

  it "Should allow for a new Board with 9 rows (default) to be created" do
    @soduko_board.rows.should == 9
  end 

  it "Should allow for a new Board with 9 columns (default) to be created" do
    @soduko_board.columns.should == 9
  end 

  it "should have a default difficulty level of 'Medium'" do
    @soduko_board.difficulty_level.should == 'Medium'
  end 

  it "should have 10 initial numbers" do
    @soduko_board.initial_number_count.should == 20
  end 

end

describe DifficultyLevel, '.new' do

  it "should exist" do
    @difficulty_level = DifficultyLevel.new
  end

  # More to be added...

end
于 2012-05-06T17:25:05.047 回答