Ruby/Class/attr accessor
Материал из Wiki.crossplatform.ru
Версия от 17:55, 13 сентября 2010; ViGOur (Обсуждение | вклад)
Содержание |
A logger
class SimpleLogger attr_accessor :level ERROR = 1 WARNING = 2 INFO = 3 def initialize @log = File.open("log.txt", "w") @level = WARNING end def error(msg) @log.puts(msg) @log.flush end def warning(msg) @log.puts(msg) if @level >= WARNING @log.flush end def info(msg) @log.puts(msg) if @level >= INFO @log.flush end end logger = SimpleLogger.new logger.level = SimpleLogger::INFO logger.info("Doing the first thing") logger.info("Now doing the second thing")
attr_accessor add accessor to a class
class Person attr_accessor :name, :age end x = Person.new x.name = "Fred" x.age = 10 puts x.name, x.age
Creating Readable and Writable Attributes: use attr_accessor
class Animal attr_accessor :color def initialize(color) @color = color end end animal = Animal.new("brown") puts "The new animal is " + animal.color animal.color = "red" puts "Now the new animal is " + animal.color
Get new defined instance methods
#!/usr/bin/env ruby class Gaits attr_accessor :walk, :trot, :canter end p Gaits.instance_methods.sort - Object.instance_methods # => ["canter", "canter=", "trot", "trot=", "walk", "walk="]
Use attr_accessor to add a new attribute and set it
class Employee attr_accessor :name def initialize @name = "" end end employee1 = Employee.new employee1.name = "Aneesha" puts employee1.name