I'm obviously new to Ruby, and programming in general, and greatly appreciate any help.
Here is my code snippet:
class Player
attr_accessor :name, :hp
def initialize(name, hp)
@name = name
@hp = hp
end
def name
@name
end
def hp
@hp
end
end
def prompt
print "> "
end
prompt; pname = gets.chomp
player = Player.new(pname, rand(20..30))
puts "#{player.name} \:\: #{player.hp} HP"
def test
puts "#{player.name} \:\: #{player.hp} HP - IN METHOD"
end
test
When run, here are the results:
$ ruby wtf.rb
> Test Name
Test Name :: 20 HP
wtf.rb:24:in `test': undefined local variable or method `player' for main:Object (NameError) from wtf.rb:27:in `<main>'
Why does my call work in the first instance, but not the second? Is it because it is now looking for a new "player" variable within the "test" method? If so, how do I go about calling the one from the class instance created earlier?
Thanks!