0
irb(main):001:0> time=Time.new
=> 2013-01-12 11:22:54 +0530
irb(main):002:0> puts time.to_s
2013-01-12 11:22:54 +0530
=> nil
irb(main):003:0> puts time.ctime
Sat Jan 12 11:22:54 2013
=> nil
irb(main):004:0> puts time.local_time
NoMethodError: undefined method `local_time' for 2013-01-12 11:22:54 +0530:Time
        from (irb):4
        from C:/Ruby193/bin/irb:12:in `<main>'
irb(main):005:0> puts time.localtime
2013-01-12 11:22:54 +0530
=> nil
irb(main):006:0> puts time.strftime("%Y-%m-%d %H:%M:%S")
2013-01-12 11:22:54
=> nil
irb(main):007:0>

Now my confusion is why that "=> nil" coming? what concept here to come it after every time function invokation?

3
Contributors
5
Replies
6
Views
4 Years
Discussion Span
Last Post by L7Sqr
0

In your case, your are printing out the local time. The function doesn't return anything after printing out the time, so the irb gets nil as return value and displays it.

Edited by Taywin

0

in what context the "nil" values will not be returned? any code snippet please?

0

If you are not running the script on irb but use ruby to run, then there shouldn't be nil returned from the function call. As I said earlier, irb keeps looking for a returned value. Because the puts does not return a value, it displays nil instead.

PS: Do you know what irb stand for? It is from interactive ruby which is a quick & dirty way to test your script. It is not supposed to be used to run your production script.

0

A point of clarification. Every operation in Ruby returns some object. Usually, it is just the result of the last operation. Consider:

irb(main):001:0> def foo &block
irb(main):002:1> block.call
irb(main):003:1> end
=> nil
irb(main):004:0> foo { nil }
=> nil
irb(main):005:0> foo { 42 }
=> 42
irb(main):006:0> foo { Hash.new(0) }
=> {}

The function definition returned a value, it just happens to be nil. Calling foo with different blocks of execution show you that the result of a block of execution is just the last value of that execution. This is true even for assignment.

irb(main):007:0> n = foo { 12 }
=> 12
irb(main):008:0> n
=> 12
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.