Beast_Code
Beast_Code

Reputation: 3247

How to ask the user for input and store the input to then display

I am attempting to create a simple interactive Ruby app. I want the user to be able to input the info and then have the program display the info entered.

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()

Right now, I am getting this error:

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

What am I missing here?

Upvotes: 1

Views: 1092

Answers (1)

jstim
jstim

Reputation: 2432

The methods you are calling are instance methods on the Player class, which means you need to create an instance of Player in order to call them.

The way you've defined your class, if you want to create a new one (with Player.new), you need to supply all three values in order for it to work (Player.new("Mike", "Center", "Spartans")). This doesn't jive with you wanting to set variables in instance methods.

To comment on your existing code, I would not do things with chomp inside the Player class. The Player class should only concern itself with the state of the player. If you want to set values I would do all of the prompting outside.

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"

Upvotes: 3

Related Questions