2014-02-14 102 views
1

我正在嘗試創建一個簡單的交互式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) 

缺少什麼我在這裏?

回答

3

您正在調用的方法是Player類中的實例方法,這意味着您需要創建一個實例Player以調用它們。

您定義班級的方式如果您想創建一個新班級(使用Player.new),則需要提供所有三個值才能使其工作(Player.new("Mike", "Center", "Spartans"))。這不會與你想在實例方法中設置變量。

要對您現有的代碼發表評論,我不會在Player類中使用chomp做任何事情。 Player課程只應關注玩家的狀態。如果你想設定值,我會做外面的所有提示。

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" 
+0

當運行代碼我得到object_oriented.rb:14:'

「:未定義的局部變量或方法'名稱」主:對象(NameError) –

+0

啊,我忘了補充'player.'到其他方法調用。在每個提示符中,您都嘗試訪問'player'對象的狀態,因此您需要在該對象上調用'name'方法。我會更新。 – jstim

+0

好吧,我明白了。另一件事是我必須使用puts player.player_info來顯示方法結果。 –

相關問題