Jinn
Jinn

Reputation: 111

Passing variable values between class methods

I am trying to figure out if it is possible to pass a value between methods in a Ruby class.

I haven't found much on my own and figured I would ask the experts. Could it be done passed as a arg/parameter to another method as well?

class PassingValues

  def initialize
    @foo = 1
  end

  def one
    @foo += 1
  end

  def two
    @foo += 1
  end

  def three
    p @foo
  end

end

bar = PassingValues.new

If I wanted this to print out foo value of 3:

bar.three

Upvotes: 0

Views: 116

Answers (3)

Mayayushi
Mayayushi

Reputation: 81

In this case @foo is an instance variable and it can be referenced (it is not passed here) in any method of the class.

When you call you create bar as an instance of the class using: PassingValues.new
it is initialized, and sets @foo to 1.

When you then call the method three using bar.three, you simply print out @foo, which is still equal to 1.

You can change your three method to increment @foo by 2, so it is now equal to 3, then print:

 def three  
    @foo += 2  
    p @foo  
 end  

Upvotes: 0

Jorge de los Santos
Jorge de los Santos

Reputation: 4643

If you want bar.three to print a 3 you will need to call before the one and two methods to ensure the variable is updated to the three so:

class PassingValues

  def initialize
    @foo = 1
  end

  def one
    @foo += 1
  end

  def two
    one
    @foo += 1
  end

  def three
    two
    p @foo
  end

end

Anyway this doesn't make sense as long as the methods will be eventually modifying the variable, so each time you call one of them the number will increase the amount expected.

Upvotes: 2

Max
Max

Reputation: 22385

Those are instance methods, not class methods. And @foo is already shared among them.

bar = PassingValues.new
bar.one
bar.two
bar.three

Upvotes: 0

Related Questions