Ruby/Class/attr reader

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

attr_reader creates one or more instance variables, with corresponding methods that return (get) the values of each method.

# attr_writer method automatically creates one or more instance variables, with corresponding methods that set the values of each method. 
class Dog
  attr_reader :bark
  attr_writer :bark
end
dog = Dog.new
dog.bark="Woof!"
puts dog.bark # => Woof!
dog.instance_variables.sort # => ["@bark"]
Dog.instance_methods.sort - Object.instance_methods # => [ "bark", "bark=" ]



attr_reader creates these accessor methods for you.

class Song 
    def initialize(name, artist, duration) 
        @name = name 
        @artist = artist 
        @duration = duration 
    end 
    def name 
        @name 
    end 
    def artist 
        @artist 
    end 
    def duration 
        @duration 
    end 
end 
song = Song.new("A", "B", 2) 
puts song.artist 
puts song.name   
puts song.duration
class Song 
    def initialize(name, artist, duration) 
        @name = name 
        @artist = artist 
        @duration = duration 
    end 
    attr_reader :name, :artist, :duration 
end 
song = Song.new("A", "B", 6) 
puts song.artist 
puts song.name  
puts song.duration



Calling the attr_accessor method does the same job as calling both attr_reader and attr_writer together, for one or more instance methods

#!/usr/bin/env ruby
class Gaits
  attr_accessor :walk, :trot, :canter
end
Gaits.instance_methods.sort - Object.instance_methods



Use attr_reader to add a new attribute and use initialize method to set it

class Employee
      attr_reader :name
      def initialize(name)  
            @name = name 
      end
end
employee1 = Employee.new("Aneesha")
puts employee1.name