How to Print the Instance Variables of a Ruby Object

advertisements
class Packet
  def initialize(name, age, number, array)
    @name = name
    @age = age
    @number = number
    @neighbors = array
  end
end

p1 = Packet.new("n1", 5, 2, [1,2,3,4])

puts p1.name

I have the above code, but whenever I execute the puts statement I get the error that name is not a method.

I don't know any other way to print the name of p1.

How to print name?


The issue here is that while you have instance variables, you haven't made them accessible. attr_reader :variable_name will let you read them, attr_writer :variable_name will let you write them, and attr_accessor :variable_name will let you do both. These are metaprogramming shortcuts built into Ruby's standard library so you don't have to write methods to read or write variables by yourself. They take a symbol, which is the instance variable name.

class Packet
  attr_reader :name, :age, :number, :array
  def initialize(name, age, number, array)
    @name = name
    @age = age
    @number = number
    @neighbors = array
  end
end

p1 = Packet.new("n1", 5, 2, [1,2,3,4])

puts p1.name