How to print ruby ​​object instance variables

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 code above, but whenever I execute the puts statement, I get an error that the name is not a method.

I do not know any other way to print the name p1.

How to print a name?

+5
source share
2 answers

The problem is that although you have instance variables, you have not made them available. attr_reader :variable_name will allow you to read them, attr_writer :variable_name will allow you to write them, and attr_accessor :variable_name will allow you to do both. These are metaprogramming shortcuts built into the Ruby standard library, so you don’t need to write methods to read or write variables yourself. They take the character, which is the name of the instance variable.

 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 
+6
source

In Ruby, instance variables and methods are completely separate. Using dot syntax for an object will only call the method. Fortunately, there are several useful methods that help you define class attributes (essentially turning an instance variable into a method):

  • attr_reader :var - creates a method called var that will return @var
  • attr_writer :var - creates a method called var= that sets the value of @var
  • attr_accessor :var - creates both specified methods

If you want name be accessible using the method, just use attr_reader :name :

 class Packet attr_reader :name # ... end 

and then:

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

Source: https://habr.com/ru/post/1208713/


All Articles