Wednesday, April 30, 2014

Instance Variables

http://www.railstutorial.org/book/rails_flavored_ruby#sec-a_user_class
In Rails, the principal importance of instance variables is that they are automatically available in the views, but in general they are used for variables that need to be available throughout a Ruby class.

Instance variables always begin with an @ sign, and are nil when undefined.

initialize, is special in Ruby: it’s the method called when we execute User.new.
https://www.ruby-lang.org/en/documentation/quickstart/2/ 
class Greeter
  def initialize(name = "World")
    @name = name
  end
  def say_hi
    puts "Hi #{@name}!"
  end
  def say_bye
    puts "Bye #{@name}, come back soon."
  end
end 
@name is an instance variable, and is available to all the methods of the class.

http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/45-more-classes/lessons/110-instance-variables


http://www.rubyist.net/~slagell/ruby/instancevars.html
An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to. Two different objects, even if they belong to the same class, are allowed to have different values for their instance variables. From outside the object, instance variables cannot be altered or even observed (i.e., ruby's instance variables are never public) except by whatever methods are explicitly provided by the programmer. As with globals, instance variables have the nil value until they are initialized. 
Instance variables do not need to be declared. This indicates a flexible object structure; in fact, each instance variable is dynamically appended to an object when it is first assigned.

***http://rubyhacking.andhapp.co.uk/2011/01/30/chapter-1.html 

No comments:

Post a Comment