Home>

I want to make a program that changes greetings depending on the time, but I can't.
Currently it is up to the bottom.

def aisatsu (name)
  time = Time.now # Get the present tense
  case time.hour
  when 5..10 # From 5 to 10
    return "Good morning, # {name}!"
  when 11..17 # From 11:00 to 17:00
    return "# {name} 's, Hello!"
  else # other than that
    return "# {name}, good evening!"
  end
end
result = aisatsu (ARGV [0])
printf ("% s% d time. \ N", result, time.hour)


The error is as below.

in `<main>': undefined local variable or method` time' for main: Object (NameError)


How can I fix it? Why not again?

  • Answer # 1

    Top-level method (function-like one)aisatsuVariables used in the definition oftimeBecause the scope extends to the end of the definition.

    That is, run outside the definitionprintfFrom thattimeYou cannot use the value of. Since it is treated as a separate variable, an error saying that it is undefined will occur.

    As another variabletimeToTime.nowYou can set the value of, but since it is used only in one place, it is directlyhourStick together,

    -printf ("% s% d time. \ N", result, time.hour)
    + printf ("% s% d time. \ N", result, Time.now.hour)

    But I should write it.

  • Answer # 2

    Variables defined in a function (local variables) are valid only in that function.

    So, at% d. I think it should be included in aisatu

  • Answer # 3

    time = Time.nowCreated intimeThe variable isaisatsuA local variable that is valid only within the method. If you try to refer to it outside the method, you will get the error "No such variable".

    I think it should be returned as the return value.

    def aisatsu (name)
      time = Time.now # Get the present tense
      case time.hour
      when 5..10 # From 5 to 10
        return "# {name}, good morning!", Time.hour
      when 11..17 # From 11:00 to 17:00
        return "# {name} 's, Hello!", time.hour
      else # other than that
        return "# {name}, good evening!", Time.hour
      end
    end
    result, hour = aisatsu (ARGV [0])
    printf (at "% s% d. \ n", result, hour)