Besnom
Besnom

Reputation: 13

Ruby: How to change the value of a variable using a method

Very first post, and very newbie question. I'm learning Ruby and trying to create a small CYOA game for training.

I want the game to have a number of lives, and each time something happens, that number of lives is changed. But I don't understand how to change the value of a variable with a method.

Here's what I did:

lives = 3
heart = "❤"
total_life = heart * lives

def add_life
  return lives + 1
end

add_life
puts "#{total_life}"

The error I get :

1: from ex36.rb:9:in <main>' ex36.rb:6:in add_life': undefined local variable or method `lives' for main:Object (NameError)

I think my main mistake is that methods create new scopes. But then I don't understand what's the best way to achieve what I want to do. Can you guys point me in the right direction?

Thanks!

Upvotes: 1

Views: 1339

Answers (2)

Amadan
Amadan

Reputation: 198496

Another option is to make a scope that makes sense. You are modeling a player (or possibly a game) - given that Ruby is strongly object-oriented, encapsulating it into a class (with lives as its instance variable) is a natural thing to do.

class Player
  HEART = "❤"

  def initialize
    @lives = 3
  end

  def life_display
    HEART * @lives
  end

  def add_life
    @lives += 1
  end
end

player = Player.new
player.add_life
puts player.life_display

Upvotes: 0

zhisme
zhisme

Reputation: 2800

In order to get it work you would need to do the following.

lives = 3
HEART = "❤"

def add_life(lives)
  return lives + 1
end

def total_lives(lives)
  HEART * lives
end

lives = add_life(lives)
puts "#{total_lives(lives)}"

Scope defines where in a program a variable is accessible. It is all about scopes, local variables are not seen in functions. They have shorter vision of variables only defined in their scope.

In order to access your lives variable you need to pass it to function. I did refactored heart -> HEART making it a constant, constants have a different scope, more like global variables $global_variable, but cannot be reassigned (ruby will nicely say you that it is incorrect)

for further reading I will leave this article

Upvotes: 1

Related Questions