Forum: Ruby Why class returns `null` but the definition not when their description ended in IRB?

Posted by Kumar R. (kumar_r)
on 2013-03-01 19:28
The below class description returns its last evaluated expression :

>> class A
>> 1+7
>> 2+4
>> end
=> 6

To return `6` which method the expression generally called?

But why the definition always `nil` ?

>> def D
>> 3+5
>> end
=> nil
Posted by Hans Mackowiak (hanmac)
on 2013-03-01 19:36
an class definition is evaluated when the code reads it,
an method definition is NOT evaluated while reading,
thats why it returns nil
Posted by Matt Mongeau (halogenandtoast)
on 2013-03-01 19:39
(Received via mailing list)
Because that's how it is implemented.


2013/3/1 Kumar R. <lists@ruby-forum.com>
Posted by Matt Mongeau (halogenandtoast)
on 2013-03-01 19:48
(Received via mailing list)
To be more explicit. The class is evaluated at definition, a method is
evaluated when it is run.


2013/3/1 Matt Mongeau <halogenandtoast@gmail.com>
Posted by Ryan Cook (cookrn)
on 2013-03-01 20:00
(Received via mailing list)
When a class or module is defined, the code inside is evaluated and the
return value of the last expression is returned. This is because you 
could
define class level attributes or constants or execute arbitrary code
relevant to the class or to prepare it.

When a method is defined as in your second example, the code inside is 
only
executed when the method is run. You could call the D() method to return 
8
as expected.

Is that helpful?
Posted by Ryan Cook (cookrn)
on 2013-03-01 20:01
(Received via mailing list)
Oops! Right on Matt -- beat me to it.
Posted by Kumar R. (kumar_r)
on 2013-03-01 20:06
Thanks to all you people.. :) BTW i put the subject wrongly. :( forgive 
me for that.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.