Tuesday 31 May 2016

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.  
  2. class Person  
  3.   attr_accessor :paid  
  4.     
  5.   def initialize  
  6.     @paid = false  
  7.   end  
  8.     
  9.   def make_payment  
  10.     puts "making payment..."  
  11.     paid = true  
  12.   end  
  13. end  
  14.   
  15. person = Person.new  
  16. person.make_payment  
  17. puts "paid=#{person.paid}" 
  18.  


Try to execute the above code and practice it by changing the variables.

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...