Alassar Alassar - 2 years ago 58
Ruby Question

Iterating through variables for object assigning

im new here and new to ruby:
I have two classes(class Friend, class Lists) and a csv-File with the name and the age. When i read in the csv-File, i create out of the whole File a new list object and want to create out of every row of the file a new friends-object.

Now my problem:
I want to assign each of these friend-objects to a variable, but i dont know how to iterate through variables.

require_relative 'friend'

class List

attr_accessor :list_name
attr_accessor :how_many

def initialize(list_name)
@list_name = list_name
@list = []

def add_friend(a_friend)

def load_friend(from_file)
File.readlines(from_file).each do |line|

require_relative 'list'

class Friend

attr_accessor :friend_name
attr_accessor :age

def initialize(friend_name,age)
@friend_name = friend_name
@age = age

def self.from_csv(string)
friend_name, age = string.split(','),age)


Here im trying to output a friend:

def value(place)
def print_list
puts @liste.to_s

puts liste1.print_list
puts liste1.wert(1)

\#<Friend:0x2b94aa8 @friend_name="Hans", @age="25\n">
\#<Friend:0x2b94a30 @friend_name="Peter", @age="20\n">
\#<Friend:0x2b949a0 @friend_name="Simon", @age="30">
\#<Friend:0x2b94a30 @friend_name="Peter", @age="20\n">

#Expected output
"Hans", 25
"Peter", 20
"Peter", 20

Answer Source

when i whant to put out the list-array he is giving me the object-id and i thought that when i assing it to a variable then i can print out the value.

If you have an array of Friend instances:

@list = ['Hans', 25),'Peter', 20),'Simon', 30),'Peter', 20)

Then printing it via

puts @list.to_s

will output a string representation of the array by calling Friend#to_s, e.g.:

friend ='Hans', 25)
#=> "#<Friend:0x007ffcc114e608>"

The object id is shown, because Friend doesn't implement its own to_s, so Object#to_s is invoked:

The default to_s prints the object’s class and an encoding of the object id.

To get the desired output, you can iterate the array via each and output the attributes one after another:

@list.each do |friend|
  puts "#{friend.friend_name}, #{friend.age}"

In the above code, friend is the variable you had in mind. While iterating your array, each assigns the current element to that variable.


Hans, 25
Peter, 20
Simon, 30
Peter, 20
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download