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 instance variables of an object can only be accessed by the instance methods of that object. The ruby instance variables do not need a declaration. This implies a flexible object structure. Every instance variable is dynamically appended to an object when it is first referenced.
Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class.
What's an instance variable? In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. Example: @fruit. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.
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
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 methodsIf 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With