Reputation: 21
I am having trouble with the class work. Im a mature age student whos trying to play catch up haha. We are using RUBY in class
# Fix up the following code that it works and produces the expected output
# in the task specification.
# Asks the user to enter their age and returns an integer age
def get_age()
puts "Enter your age in years: "
age = gets.to_i
return age
end
# takes a prompt and displays it to the user then returns the
# entered string
def get_string()
puts "Enter your name: "
name = gets
return name
end
# Calculate the year born based on the parameter age and print that out
# along with the name of the user
def print_year_born(age)
year_born = Date.today.year - get_age
puts "You were born in: " + year_born
return year_born
end
def main
age = get_age()
name = get_string()
print_year_born
(age)
end
main
I am having trouble in the line ..
def print_year_born = Date.today.year - get_age
puts "You were born in: " + year_born
return year_born
end
The issue im having is age has already been found but it's in the other procedure get_age how do I call get_age in this procedure?
Thanks in advance- Student
Upvotes: 1
Views: 323
Reputation: 11
I'm doing the same task. I might be a bit late to answer but you need to define date at the beginning of the coding. In row three you need to enter the following: require 'date'
This will fix your issue. However I have an issue with: def print_year_born(age) year_born = Date.today.year - age puts(name.to_s + "You were born in: " + year_born.to_s) end
The outcome should be: "name" you were born in: "year". I can't figure out how to get the name it appear. NOTE: Coding is the exact same as the above question
Upvotes: 1
Reputation: 1064
This is a representative answer to your requirement. You need to familiarise yourself with the concept of nested procedure calls. These are at the heart of OOP. The idea being that the message is all the caller needs from the provider and that the caller speaks directly to the provider, who may make their own requests of other providers, without intervening procedural code to hold state or values.
def get_age()
puts "Enter your age in years: "
age = gets.to_i
return age
end
require 'date'
def print_year_born
year_born = Date.today.year - get_age
puts "You were born in: #{year_born}"
# or even more simply
puts "You were born in: #{Date.today.year - get_age}"
end
print_year_born
Enter your age in years:
12
You were born in: 2008
Enter your age in years:
12
You were born in: 2008
Upvotes: 0
Reputation: 36880
As you noted, you got the age in get_age
So instead of
year_born = Date.today.year - get_age
which requests it again, you need to do
year_born = Date.today.year - age
age
being the argument that you passed into the print_year_born method
Plus it may be a typo, but you want
print_year_born(age)
as one line
Upvotes: 1