Alassar Alassar - 5 months ago 20
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 = []
end

def add_friend(a_friend)
@list.push(a_friend)
end

def load_friend(from_file)
File.readlines(from_file).each do |line|
add_friend(Friend.from_csv(line))
end
end
end


require_relative 'list'

class Friend

attr_accessor :friend_name
attr_accessor :age

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

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

end


Here im trying to output a friend:

#-------------------------
def value(place)
@list[place].to_s
end
def print_list
puts @liste.to_s
end

#-------------------------
puts liste1.print_list
puts liste1.wert(1)

#-------------------------
#Output
\#<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
"Simon",30
"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 = [
  Friend.new('Hans', 25),
  Friend.new('Peter', 20),
  Friend.new('Simon', 30),
  Friend.new('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 = Friend.new('Hans', 25)
friend.to_s
#=> "#<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}"
end

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

Output:

Hans, 25
Peter, 20
Simon, 30
Peter, 20