Ruby tutorial session 6

Variable/Method Ambiguity Gotcha

In the below mentioned program we are defining a variable called paid, while initializing the class object we are creating instance variable default value is false.

We have make_payment instance method defined here and inside that method we assigning value to the paid variable to true, just notice that in this method we are not overriding/replacing the actual instance variable so after calling the make_payment actual instance variable value won't change, if you try to print the paid value of instance will be false.
  1. class Person  
  2.   attr_accessor :paid  
  3.     
  4.   def initialize  
  5.     @paid = false  
  6.   end  
  7.     
  8.   def make_payment  
  9.     puts "making payment..."  
  10.     paid = true  
  11.   end  
  12. end  
  13.   
  14. person = Person.new  
  15. person.make_payment  
  16. puts "paid=#{person.paid}"
  17.  
  18. Try to execute the above code and practice it by changing the variables.
  19.  
  20. Hope you will understand, i will get back to you with new concept. 

No comments:

Post a Comment

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...