如何询问用户输入并存储输入然后显示

时间:2014-02-14 05:01:18

标签: ruby

我正在尝试创建一个简单的交互式Ruby应用程序。我希望用户能够输入信息,然后让程序显示输入的信息。

class Player
  def initialize(name, position, team)
    @name = name
    @position = position
    @team = team
  end

  def get_player_info
    puts "Who is your favorite NFL player?"
    name = gets.chomp

    puts "What position does #{name} play?"
    position = gets.chomp

    puts "What team does #{name} play for?"
    team = gets.chomp
  end

  def player_info()
    "#{@name} plays #{@position} for the #{@team}."
  end

end

# Get player info by calling method
get_player_info()

# Display player info
player_info()

现在,我收到了这个错误:

object_oriented.rb:26:in `<main>': undefined method `get_player_info' for main:Objec
t (NoMethodError)

我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

您调用的方法是Player类上的实例方法,这意味着您需要创建Player的实例才能调用它们。

您定义课程的方式,如果您想创建一个新课程(使用Player.new),您需要提供所有三个值才能使其正常工作(Player.new("Mike", "Center", "Spartans"))。想要在实例方法中设置变量,这并不存在。

要评论您现有的代码,我不会在chomp类中使用PlayerPlayer类应仅关注播放器的状态。如果你想设置值,我会在外面做所有的提示。

class Player
  attr_accessor :name, :position, :team

  def player_info
    "#{name} plays #{position} for #{team}"
  end
end

player = Player.new

puts "Who is your favorite NFL player?"
player.name = gets.chomp

puts "What position does #{player.name} play?"
player.position = gets.chomp

puts "What team does #{player.name} play for?"
player.team = gets.chomp

puts player.player_info
# => "Mike plays Center for Spartans"
相关问题