0

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"[email protected]    #will not work as I want 
end 

Thank you for ur time and effort and if you need any clarification please let me know

1
  • In what class did you try to define this to_s? Commented Mar 21, 2022 at 12:59

2 Answers 2

2

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(',')
Sign up to request clarification or add additional context in comments.

Comments

-1

Try this,

array.each do |per|
 "#{per.name} #{per.LASTN}"
end

For more info check Interpolation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.