each_with_index

J

Jane O'Maley

Hi, I'm trying to get my file to take in a list of names (a firstname,
surname and middlename) and to then list each part of the name with an
index. For example one name "John, Smith, Paul" should be printed as
1.John
2.Smith
3.Paul

I can list the index as 1.John Smith Paul but am unsure on how to list
each part of the name seperately, does anyone have any ideas?

Attachments:
http://www.ruby-forum.com/attachment/4262/Person.txt
 
M

Marnen Laibow-Koser

Jane said:
Hi, I'm trying to get my file to take in a list of names (a firstname,
surname and middlename) and to then list each part of the name with an
index. For example one name "John, Smith, Paul" should be printed as
1.John
2.Smith
3.Paul

I can list the index as 1.John Smith Paul but am unsure on how to list
each part of the name seperately, does anyone have any ideas?

Create one array with all the strings in it. Or define Person#each or
Person#to_a.


Best,
 
J

Jeremy Woertink

Jane said:
Hi, I'm trying to get my file to take in a list of names (a firstname,
surname and middlename) and to then list each part of the name with an
index. For example one name "John, Smith, Paul" should be printed as
1.John
2.Smith
3.Paul

I can list the index as 1.John Smith Paul but am unsure on how to list
each part of the name seperately, does anyone have any ideas?

"John, Smith, Paul".split(", ").each_with_index do |name, index|
puts "#{index + 1}. #{name}\n"
end


~Jeremy Woertink
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,195
Latest member
tewan

Latest Threads

Top