Thursday, November 1, 2012

attr_ methods and instance methods



Instead of doing this...
class Car
  def set_sound(sound)
    @sound = sound
  end

  def get_sound
    @sound
  end

volkswagen = Car.new
  #--You are creating an instance(object) of Car

volkswagen.set_sound = "Beep!" 
  #--You're telling the computer that this is the sound(attribute) 
      that this particular Car(volkswagen) will make.

volkswagen.get_sound  #=> "Beep!"
  #--You're telling the computer that this Car(volkswagen) will now use that sound.

Do this instead...
class Car
  attr_accesor :sound
end

volkswagen = Car.new
volkswagen.sound = "Beep!"
volkswagen.sound  #=> "Beep!"

Here's more...
class Animal
    attr_accessor :name
    attr_writer :color
    attr_reader :legs, :arms

    def color
 "The color is #{@color}."
    end

    def setup_limbs
 @legs = 4
 @arms = 0
    end

    #--if you don't want to use attr_ methods, do these...
    def noise=(noise)
 @noise = noise
    end

    def noise
 @noise
    end
end

animal1 = Animal.new

animal1.name = "Steve"
puts animal1.name

animal1.noise = "MOO"
puts animal1.noise

animal1.color = "black"
puts animal1.color

animal1.setup_limbs
puts animal1.legs

Better yet, use instance methods...
class Animal
    attr_accessor :name, noise
    attr_writer :color
    attr_reader :legs, :arms

    def color
        "The color is #{@color}."
    end

    def initialize(legs = 4, arms = 0) #--initialize method
        #--use with attr_reader
        @legs = legs
        @arms = arms
    end
end

animal1 = Animal.new("MOO")

animal1.name = "Steve"
puts animal1.name

puts animal1.noise

animal1.color = "black"
puts animal1.color

puts animal1.legs

Source--Lynda.com Ruby Essential Training

No comments:

Post a Comment