umdcoder
umdcoder

Reputation: 147

How to print the instance variables of a ruby object

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?

Upvotes: 5

Views: 12131

Answers (2)

Mario
Mario

Reputation: 2942

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

Upvotes: 10

August
August

Reputation: 12558

In Ruby, instance variables and methods are completely separate. Using dot-syntax on an object will only call a method. Fortunately, there are a few utility methods to help define attributes on classes (essentially turning an instance variable into a method):

  • attr_reader :var - creates a method named var, which will return the value of @var
  • attr_writer :var - creates a method named var=, which will set the value of @var
  • attr_accessor :var - creates both of the above methods

If you want name to be accessible through a method, simply use attr_reader :name:

class Packet
  attr_reader :name

  # ...
end

and then:

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

Upvotes: 5

Related Questions