Adding more accessors : instance variables « Class « Ruby






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)

 








Related examples in the same category

1.In Ruby, you prefix instance variables with an at sign @
2.Using a Constructor to Configure Objects
3.Print out the instance variable
4.class variable vs object variable