Zenki N. wrote:
Thanks All for helping me out on this…
Now…here’s another issue…Say i want to display the retired players
last name in alphabetical order with its contents. Noticed this time
some has middle names, initials.
How would I tackle this?
Sorry, I’ve looked thru many books and have a difficult time solving
this…
retired_players = <<PLAYERS
Mike Anthony Gallego, 1985-1997
Calvin Edwin Ripken, Jr., 1981-2001
Tony K. Gwynn, 1982-2004
Dennis Eckersley, 1975-1998
PLAYERS
Thanks,
My attempt:
retired_players = <<PLAYERS
Mike Anthony Gallego, 1985-1997
Calvin Edwin Ripken, Jr., 1981-2001
Tony K. Gwynn, 1982-2004
Dennis Eckersley, 1975-1998
PLAYERS
#A container for each player’s data:
Player = Struct.new(:last, :first_middle, :years)
#An array to hold each Player:
players = []
#Divide the string into lines:
lines = retired_players.split("\n")
lines.each do |line|
pieces = line.split(’,’)
#Extract the years played:
years = pieces[-1].strip()
#Extract the title, e.g. .jr, .sr
if pieces.length == 3 #then player has a title like .jr, .sr
title = pieces[1].strip()
else
title = false
end
#Extract the names:
names = pieces[0].split()
last = names[-1]
first_middle = names[0…-2].join(" “)
if title
last = sprintf(”%s %s", last, title)
end
#Create a new Player with the above data:
players << Player.new(last, first_middle, years)
end
#Sort the Player objects in the players array by last name:
sorted_players = players.sort do |p1, p2|
p1.last<=>p2.last
end
#Output the sorted players:
sorted_players.each do |player|
puts sprintf("%s, %s %s", player.last, player.first_middle,
player.years)
end
–output:–
Eckersley, Dennis 1975-1998
Gallego, Mike Anthony 1985-1997
Gwynn, Tony K. 1982-2004
Ripken Jr., Calvin Edwin 1981-2001