Reputation: 407
There aren't any error messages showing up once the code is run, I've resolved all of those before posting here. This is just a simple greeting with a few methods, which takes the current time into account and asks for the user's name, but for some reason there's a hole where the time variable should be in the greeting. This is my Ruby code here:
def determine_current_hour
current_time = Time.new
current_hour = current_time.hour
end
def greeting(name)
current_hour = determine_current_hour
if(current_hour > 3 && current_hour < 12)
time = "morning"
elsif(current_hour > 12 && current_hour < 18)
time = "afternoon"
elsif(current_hour > 18 || current_hour < 2)
time = "evening"
end
puts "Good #{time}, #{name.capitalize}!"
end
puts "What is your name?"
name = gets
greeting(name)
And this is the resulting input and output:
What is your name?
Ruby
Good , Ruby
!
It seems airtight to me but I must be missing something. Any help would greatly be appreciated!
Upvotes: 0
Views: 33
Reputation: 106067
As Greg Beech correctly points out, some hours are wrong because your conditions exclude them. For example, your first condition says current_hour < 12
and your second condition says current_hour > 12
, but if current_hour
is equal to 12 it meets neither of those conditions. To fix it, either replace the comparison operator in the first condition with <=
or in the second with >=
:
def greeting(name)
current_hour = determine_current_hour
if current_hour >= 3 && current_hour < 12
time = "morning"
elsif current_hour >= 12 && current_hour < 18
time = "afternoon"
elsif current_hour >= 18 || current_hour < 3
time = "evening"
end
puts "Good #{time}, #{name.capitalize}!"
end
This is pretty verbose, though. Might I suggest a more idiomatic approach using Ruby's versatile case
construct?
def current_day_part
case Time.new.hour
when 3..11 then "morning"
when 12..17 then "afternoon"
else "evening"
end
end
def greeting(name)
puts "Good #{current_day_part}, #{name.capitalize}!"
end
Upvotes: 1
Reputation: 136717
Your conditions do not account for the hour being 2, 3, 12 or 18 because they are all exclusive checks. In any of those hours you will see the output you describe.
Upvotes: 1