Как инициализировать класс в классе Ruby - PullRequest
0 голосов
/ 22 февраля 2019

Я учусь на Руби, и я застрял, поэтому у меня есть вопрос.Как инициализировать класс в другом классе, и возможно ли это?Я пытаюсь написать простую игру "Dog's Runs".Вот классы:

Класс DOG с информацией о собаках.

class DOG
  def initialize(breed,name,weight=0,height=0,speed=0)
    @the_weight = weight
    @the_height = height
    @the_breed = breed.capitalize
    @the_name = name.capitalize
    @the_speed = speed
  end

  def to_s
    "                    DOG INFORMATION
                  His name is: #{@the_name}
                  His breed is: #{@the_breed}
                  His weight is: #{@the_weight} cm
                  His height is: #{@the_height} kg
              His average speed is: #{@the_speed} km/h
        "
  end
end

класс GAME

class GAME
    def initialize_game
       luckS = rand(0..10)
       luckR = rand(0..10)
       luckW = rand(0..10)
        if choose_dog == "Steve\n" or choose_dog == "steve\n" or choose_dog == "whippet\n" or choose_dog == "Whippet\n"
            if choose_rate == 3.33
                puts "You choosed , your rate is 3.33!"
                puts "The game starts!"
                if luckS > luckR and luckS > luckW
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
            if choose_rate == 6.66
                puts "You choosed , your rate is 6.66!"
                puts "The game is starts!"
                if luckS > luckR and luckS > luckW
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
            if choose_rate == 10.00
                puts "You choosed , your rate is 10.00!"
                puts "The game is starts!"
                if luckS > luckR and luckS > luckW
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
        end
        if choose_dog == "Richard\n" or choose_dog == "richard\n" or choose_dog == "greyhound\n" or choose_dog == "Greyhound\n"
            puts "Great pick!"
            puts "Choose rate!"
            puts "First rate is 3.33 , please write in 3.33 if you want to pick that rate"
            puts "Second rate is 3.33 , please write in 6.66 if you want to pick that rate"
            puts "Third rate is 3.33 , please write in 10.00 if you want to pick that rate"
            if choose_rate == 3.33
                puts "You choosed , your rate is 3.33!"
                puts "The game is starts!"
                if luckR > luckS and luckR > luckW
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
            if choose_rate == 6.66
                puts "You choosed , your rate is 6.66!"
                puts "The game is starts!"
                if luckR > luckS and luckR > luckW
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
            if choose_rate == 10.00
                puts "You choosed , your rate is 10.00!"
                puts "The game is starts!"
                if luckR > luckS and luckR > luckW
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
        end
        if choose_dog == "Whilley\n" or choose_dog == "whilley\n" or choose_dog == "saluki\n" or choose_dog == "Saluki\n"
            puts "Great pick!"
            puts "Choose rate!"
            puts "First rate is 3.33 , please write in 3.33 if you want to pick that rate"
            puts "Second rate is 3.33 , please write in 6.66 if you want to pick that rate"
            puts "Third rate is 3.33 , please write in 10.00 if you want to pick that rate"
            if choose_rate == 3.33
                puts "You choosed , your rate is 3.33!"
                puts "The game is starts!"
                if luckW > luckS and luckW > luckR
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
            if choose_rate == 6.66
                puts "You choosed , your rate is 6.66!"
                puts "The game is starts!"
                if luckW > luckS and luckW > luckR
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
            if choose_rate == 10.00
                puts "You choosed , your rate is 10.00!"
                puts "The game is starts!"
                if luckW > luckS and luckW > luckR
                    puts "You win!"
                    puts "Take your cash."
                    money = money + (money*choose_rate)
                else
                    puts "You lose"
                    money = money - (money*choose_rate)
                end
            end
        end
    end
end

И другой код, который должен запускать класс GAME:

puts "Hello to our \"Dog's Runs!\""
        money = 1000
        puts "Here's information about our dogs"
        dogs=[DOG.new("whippet","Steve",15,48,50),DOG.new("greyhound","Richard",34,73,70),DOG.new("saluki","Whilley",20,61,60)]
        puts dogs
        puts "Please , write in dog's name or breed:"
        choose_dog = gets.to_s
        puts "Great pick!"
        puts "Choose rate!"
        puts "First rate is 3.33 , please write in 3.33 if you want to pick that rate"
        puts "Second rate is 3.33 , please write in 6.66 if you want to pick that rate"
        puts "Third rate is 3.33 , please write in 10.00 if you want to pick that rate"
        choose_rate = gets.to_f
        GAME.new.initialize_game

Я изменил большую часть кода, но я просто не могу инициализировать этот класс GAME, я написал GAME.new.initialize_game с именем_класса и методом, но это все равно не сработает.

Ответы [ 2 ]

0 голосов
/ 22 февраля 2019

Я запустил ваш код, и есть четкое сообщение об ошибке.Может быть, вы запускаете код каким-либо образом, который не показывает сообщение об ошибке?

Great pick!
Choose rate!
First rate is 3.33 , please write in 3.33 if you want to pick that rate
Second rate is 3.33 , please write in 6.66 if you want to pick that rate
Third rate is 3.33 , please write in 10.00 if you want to pick that rate
6.66
/Users/schwern/tmp/test.rb:26:in `initialize_game': undefined local variable or method `choose_dog' for #<GAME:0x00007f9a7208a5c0> (NameError)
    from /Users/schwern/tmp/test.rb:171:in `<main>'

Game#initialize_game ссылается на choose_dog и choose_rate и money.Хотя это переменные в основной программе, они больше нигде не доступны.Это позволяет вам изолировать части программы друг от друга.Если вы хотите использовать их в методе, они должны быть переданы.

# In GAME
def initialize_game(choose_dog, choose_rate, money)

# When calling it.
GAME.new.initialize_game(choose_dog, choose_rate, money)
0 голосов
/ 22 февраля 2019

Я догадываюсь, что вы спрашиваете, но, глядя на ваш код и комментарии, вы пытаетесь включить собак, которых вы создали (в своем последнем фрагменте), в «игру», которую вы создали.

Существует несколько изящных способов сделать это, следуя разным шаблонам дизайна, но я буду придерживаться чего-то более простого, пока вы учитесь: скажите классу Game, что собака или собакаСуществовать:

class Dog
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

class Game
  attr_reader :dogs

  def initialize(*dogs)
    @dogs = dogs
  end

  def play
    puts "For tonights race we have:"
    dogs.each do |dog|
      puts dog.name
    end
  end
end

d1 = Dog.new('Joe')
d2 = Dog.new('Sally')
d3 = Dog.new('Steve')

game = Game.new(d1, d2, d3)

game.play

При создании игры вы можете создать собак автоматически:

class Dog
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

class Game
  attr_reader :dogs

  def initialize
    load_dogs
  end

  def play
    puts "For tonights race we have:"
    dogs.each do |dog|
      puts dog.name
    end
  end

  private

  def load_dogs
    @dogs = []
    @dogs << Dog.new('Joe')
    @dogs << Dog.new('Sally')
    @dogs << Dog.new('Steve')
  end
end

game = Game.new

game.play

Затем вы можете интегрировать свой выбор в код игры:

class Dog
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

class Game
  attr_reader :dogs

  def initialize
    load_dogs
  end

  def play
    puts "For tonights race we have:"
    dogs.each do |dog|
      puts dog.name
    end

    puts

    choose_your_dog
  end

  private

  def choose_your_dog
    puts "Which dog do you want"
    @choice = gets.to_s.strip
    puts "You choose #{@choice}; great choice!"
  end

  def load_dogs
    @dogs = []
    @dogs << Dog.new('Joe')
    @dogs << Dog.new('Sally')
    @dogs << Dog.new('Steve')
  end
end

game = Game.new

game.play
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...