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
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
an class definition is evaluated when the code reads it,
an method definition is NOT evaluated while reading,
thats why it returns nil
To be more explicit. The class is evaluated at definition, a method is
evaluated when it is run.
2013/3/1 Matt M. [email protected]
Oops! Right on Matt – beat me to it.
Thanks to all you people… BTW i put the subject wrongly. forgive
me for that.
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?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs