Ruby/Class/instance variables
Материал из Wiki.crossplatform.ru
Версия от 17:55, 13 сентября 2010; ViGOur (Обсуждение | вклад)
Содержание |
Adding more accessors
#!/usr/bin/env ruby class Names def initialize( given, family, nick, pet ) @given = given @family = family @nick = nick @pet = pet end # these methods are public by default def given @given end def family @family end # all following methods private, until changed private def nick @nick end # all following methods protected, until changed protected def pet @pet end end class Address < Names attr_accessor :street, :city, :state, :country end a = Address.new("a","b","c","d") puts a.respond_to?(:given_name)
class variable vs object variable
#!/usr/bin/env ruby class Repeat @@total = 0 def initialize( string, times ) @string = string @times = times end def repeat @@total += @times return @string * @times end def total "Total times, so far: " + @@total.to_s end end data = Repeat.new( "a ", 8 ) ditto = Repeat.new( "A! ", 5 ) ditty = Repeat.new( "R. ", 2 ) puts data.repeat puts data.total puts ditto.repeat puts ditto.total puts ditty.repeat puts ditty.total
In Ruby, you prefix instance variables with an at sign @
# An instance variable is one in which you can store the data in an object - an instance of a class is an object. # Instance variables hold their values for as long as the object is in existence. # That"s what helps make objects self-contained: the capability to store data. class Animal def initialize @color = "red" end end
Print out the instance variable
class Hello def initialize( name ) @name = name end def hello_matz puts "Hello, " + @name + "!" end end hi = Hello.new( "Matz" ) hi.hello_matz # => Hello, Matz!
Using a Constructor to Configure Objects
# An instance variable is a variable that is referenced via an instance of a class # An instance variable belongs to a given object. # An instance variable is prefixed by a single at sign (@) class Animal def initialize(color) @color = color end def get_color return @color end end animal = Animal.new("brown") puts "The new animal is " + animal.get_color