newkidontheblock
newkidontheblock

Reputation: 65

Error when calling a method with command line argument

I want to pass a command line argument to my program and then reference the argument in a method I'm calling but I'm receiving the undefined local variable or method error player_name.

I'm very new to Ruby, so this might be a basic question but I try to understand how to use ARGV properly. Is it not possible to use the input the user provides as a command line argument in a method and then call this method? What am I missing?

player_name = ARGV.first

def start
    puts "Hey #{player_name}, do you want to go left or right?"
    print "> "
end

start

Upvotes: 0

Views: 29

Answers (2)

Ursus
Ursus

Reputation: 30056

Your usage of ARGV is correct. Simply player_name is not defined in the start method. If you want to keep your method pass to it the variable

def start(player_name)
  puts "Hey #{player_name}, do you want to go left or right?"
  print "> "
end

first_argument = ARGV.first
start(first_argument)

Note: I changed a variable name and moved a line to show you that they're not the same variables. You're passing it around. I think it's clearer now

Upvotes: 1

Yurii
Yurii

Reputation: 691

In addition to previous answer checkout this explanation of variable scopes in ruby: https://www.natashatherobot.com/ruby-variable-scope/

Upvotes: 0

Related Questions