I have tackled Java and C programming in the past (amateur level) and I have come across arrays before. It took a while to get around understanding array. All I know is that it is similar to a matrix in mathematics.
But what do you do in situations where you want to store data that are "pairs". For example a name of a person and their corresponding birthdays or a name of person and their corresponding addresses? Sometimes it is better to use the class Hash than Array in this case.
Let's say we have the following list:
John Arturo, 16 May 1979
Jacob Joaqim, 18 Oct 1992
Tyson Mayer, 22 Dec 1986
In Ruby, you can store these data as pairs:
birth_date = {}
birth_date['John Arturo'] = '16 May 1979'
birth_date['Jacob Joaqim'] = '18 October 1992'
birth_date['Tyson Mayer'] = '22 December 1986'
So if you want to know a person's birthday on that list you can do the following:
puts 'Whose birthday do you want to know?'
name = gets.chomp
date = birthday[name] # easy retrieval of the date according to # the name
Displaying the date:
if date == nil
puts 'Ooohh... I don't know that one...'
else
puts date[0..5] # this excludes the year in the output
end
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment