I have an array of Persons (class contain name and lastname and id ) what I have to do is to return a string form this array but in a specific format an example will be more explicative
array=[PERS1,PERS2]
I need this as a return value : "The name of all persons : " PERS1.name PERS1.LASTN " , " PERS2.name PERS2.LASTN ","
I know this method
array.each{ |per|
#but this will not return the format ,and with each I think I can only print (I'm new in the ruby field
}
all of this because I need it when overriding to_s , because I need to provide a string -> to_s
def to_s
"THE name of all preson" @array.each #will not work as I want
end
Thank you for ur time and effort and if you need any clarification please let me know
CodePudding user response:
Try this,
array.each do |per|
"#{per.name} #{per.LASTN}"
end
For more info check Interpolation
CodePudding user response:
each
just iterates over a collection and returns the collection itself. You may want to use map
and join
the result.
array.map { |person| "#{person.name} #{person.lastn}" }.join(',')
Or if you modify your Person
class it can be even simpler.
# I assume that the name of the class is Person and name and lastn are always present
class Person
def full_name
"#{person.name} #{person.lastname}"
end
end
# Then you can call this method on `map`.
array.map(&:full_name).join(',')