Home > front end >  How to use the ruby time function in a method (if statement)?
How to use the ruby time function in a method (if statement)?

Time:10-07

Hi I'm doing this question and it is not passing the automated tests and would love to know where i'm going wrong? Many thanks.

question: The hello function Should return (not puts) 'Good morning!' between 09:00 and 12:00 and 'Good afternoon!' between 12:00 and 16:00 and 'Hello!' at all other times

def hello
    t = Time 
    if t = (0900..1200)
        return 'Good morning!'
    elsif t = (1201..1600)
        return 'Good afternoon!'
    else
        return "Hello!"
    end
    
end
hello 

CodePudding user response:

This looks like an assignment so I'll do my best to not just give the answer. There are a few misconceptions in your code and incorrect statements causing it to behave the way it is.

t = Time assigns the class Time to t, it does not generate a time. You can use irb or even on online REPL to learn more information about what a variable holds in realtime.

t = Time
t       #=> Time
t.class #=> Class
 

You should look into the ruby Time class, you'll be interested in the methods #new, #now, and potentially #parse.

Your if statement is not checking equality, it's assigning a range of integers to t. A range is a truthy value, so if the code ran the first conditionally would always be true. The range syntax is incorrect, ranges do not support leading zeros.

t = (0900..1200) #=> Error, leading zero
t = (900..1200)
t                #=> 900..1200
t.class          #=> Range

For this area you'll want to get more familiar with the difference between = assignment, and == equality. It's also worth noting that integers and time are different classes, so you cannot compare a raw time with a range of integers.

Fixing the time generation and time comparison should get you on the right path for passing tests.

CodePudding user response:

def greetings
  t = Time.now
  mid_noon = t.change({ hour: 12 })
  
  if (mid_noon - 3.hours .. mid_noon).cover? t
    return 'Good Morning!'
  elsif (mid_noon .. mid_noon   4.hours).cover? t
    return 'Good Afternoon!'
  end
  return "Hello!"
end

greetings
  • Related