Pending Pending - 2 months ago 7
Ruby Question

How do I get the value from one method into another method in the same class?

How can I get the value from one method into another method in the same class so I can use it?

Example:

def initialize var1
@var1 = var1
end

def method_a var2
#Here how can I use var1 to add it to var1 to make a var2
var2 = var1 + var1?
end

def method_b
#display
"#{@var1}, "#{var2}"
end


So I'd be making a second variable in
method_a
that was not initialized and then display it in
method_b
.

Answer
def method_a
  @var2 = @var1 + @var1 # or: @var2 = @var1*2
end

def method_b
  puts "#{@var1}, #{@var2}"
end

or someth like it:

class Foo
  def initialize var1
    @var1 = var1
    @var2 = method_a #or change this string to call method_a, so just: method_a and this return @var2 = @var1*2
  end
  def method_a
    @var1*2 #and there you should use variable @var2 = @var1 + @var1 (or @var1*2)
  end
  def method_b
    p "#{@var1}, #{@var2}"
  end
end


#=> boo = Foo.new(1)
#=> boo.method_b
#=> 1, 2
Comments