难以放置信息并从数组中提取信息

时间:2019-04-26 07:14:09

标签: ruby

我正在创建一个程序,该程序为狗创建一条记录,该记录具有以下属性(id,繁殖年份和名称)。我必须使用数组来存储3条狗的属性,然后将它们打印到终端

require './input_functions'




class Dog
  attr_accessor :id, :breed, :year_born, :name

  def initialise (id, breed, year_born, name)
    @id = id
    @breed = breed
    @year_born = year_born
    @name = name
  end
end


# Complete the missing code below

# Note: If your tasks requires outputting a floating point number you may wish to use the following:
# print out my_variable with 2 decimal places:
# printf("$%.2f\n", my_variable)
def read_dog()
  puts "Enter the ID of your dog"
  $dog_id = gets.to_s
  puts "Enter the Breed of your dog"
  $dog_breed = gets.to_s
  puts "Enter the birth year of your dog"
  $dog_year_born = gets.to_s
  puts "Enter the name of your dog"
  $dog_name = gets.to_s

end

def display_dog
  puts $dog_id + "The dog ID is an Integer which is unique to your dog"
  puts $dog_breed + "The dog breed is a String which defines the ancestors of your dog"
  puts $dog_year_born + "The year born is an Integer which contains what year your dog was born"
  puts $dog_name + "The dog name is a String which contains what your dog's name is"
end

def read_dogs
  dogs = Array.new
  index = 0
  while (index < 3)
    dogs << read_dog[index]
    index = index + 1
  end
  return dogs
end

def display_dogs(dogs)

  index = 0
  while (index < 3)
    dogs[display_dog.to_i]
  index = index + 1
  end

end



def main
    dogs = read_dogs
  display_dogs(dogs)
end


main

我希望得到的结果是在程序要求您3次输入所有信息之后,它将随后将所有信息显示给用户。相反,将只显示最后输入的一组数据,并且将其显示三次。显然,这与我如何从数组中存储或提取数据有关,但我不知道那是什么。

2 个答案:

答案 0 :(得分:0)

首先,您必须从read_dog方法返回一些值

def read_dog()
  puts "Enter the ID of your dog"
  $dog_id = gets.to_s
  puts "Enter the Breed of your dog"
  $dog_breed = gets.to_s
  puts "Enter the birth year of your dog"
  $dog_year_born = gets.to_s
  puts "Enter the name of your dog"
  $dog_name = gets.to_s

  return [$dog_id, $dog_breed, $dog_year_born, $dog_name]
end

让我在其他方面进行更新,因为它仅打印最新信息 顺便说一句,我目前在您的代码段中看不到使用Dog类代码

答案 1 :(得分:0)

我会做这样的事情,它会做应该做的事情。

class Dog
    attr_accessor :id, :breed, :year_born, :name

    def initialize
        puts "Enter the ID of your dog"
        @id = gets.to_s
        puts "Enter the Breed of your dog"
        @breed = gets.to_s
        puts "Enter the birth year of your dog"
        @year_born = gets.to_s
        puts "Enter the name of your dog"
        @name = gets.to_s
    end

    def self.ask_for_dogs
        all_dogs = []
        3.times do
            all_dogs << Dog.new
        end
        all_dogs
    end

    def self.display(dogs)
        dogs.each do |dog|
            puts "Id: #{dog.id}"
            puts "Name: #{dog.name}"
            puts "Breed: #{dog.breed}"
            puts "Year born: #{dog.year_born}\n"
        end
    end
end

dogs = Dog.ask_for_dogs
Dog.display(dogs)

通过访问dog对象的属性,可以保存可以立即全部打印出来的对象。