Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby : if i declare a variable in a method does another method in the same class know it exists?

If i have a method called roll (as in a dice) and it has a variable called number.

can another method in the same class called stats use that variable in it ??

like image 368
Ger Crowley Avatar asked Jun 07 '26 10:06

Ger Crowley


1 Answers

You mean like this?

class Die
  def roll
    @number = 5
  end

  def stats
    puts @number
  end
end

d = Die.new
d.roll
d.stats # prints 5
like image 190
Brian Genisio Avatar answered Jun 09 '26 01:06

Brian Genisio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!