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)
缺少什麼我在這裏?
當運行代碼我得到object_oriented.rb:14:'「:未定義的局部變量或方法'名稱」主:對象(NameError) –
啊,我忘了補充'player.'到其他方法調用。在每個提示符中,您都嘗試訪問'player'對象的狀態,因此您需要在該對象上調用'name'方法。我會更新。 – jstim
好吧,我明白了。另一件事是我必須使用puts player.player_info來顯示方法結果。 –