0

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

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  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.