[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Difference between Class.new and class

Levin Alexander

7/14/2005 9:46:00 PM

Hi,

why do class definitions with the keyword "class" return nil and not the
class itself?

>> class Foo
>> def foo
>> puts "in Foo"
>> end
>> end
=> nil

and what is the difference to:

>> Bar = Class.new do
>> define_method(:bar) do
>> puts "in Bar"
>> end
>> end
=> Bar

Thank you,
Levin


6 Answers

Robert Klemme

7/14/2005 10:10:00 PM

0

Levin Alexander <levin@grundeis.net> wrote:
> Hi,
>
> why do class definitions with the keyword "class" return nil and not
> the class itself?

Because the last expression in the block is returned:

>> class Foo; self end
=> Foo
>> class Bar; 123 end
=> 123

Method definitions ("def ...") return nil.

> >> class Foo
> >> def foo
> >> puts "in Foo"
> >> end
> >> end
> => nil
>
> and what is the difference to:
>
> >> Bar = Class.new do
> >> define_method(:bar) do
> >> puts "in Bar"
> >> end
> >> end
> => Bar

The former is the standard syntax for defining classes. The latter can be
used to create anonymous classes.

>> Irks = Class.new
=> Irks
>> ui = Class.new
=> #<Class:0x10189d98>

A disadvantage of the latter approach is that you cannot define methods that
receive a block. There is no equivalent (yet) for "def foo(&b) b.call(1)
end" with define_method, because you cannot do define_method(:foo) {|&b|
b.call(1)}. Also, you cannot have default values for method arguments with
define_value. The bottom line is: use the block form only if you need
anonymous classes or have to otherwise. HTH

Kind regards

robert

Pete Elmore

7/14/2005 10:22:00 PM

0

Levin Alexander wrote:
> Hi,
>
> why do class definitions with the keyword "class" return nil and not
> the class itself?
>
> >> class Foo
> >> def foo
> >> puts "in Foo"
> >> end
> >> end
> => nil
irb(main):001:0> class X
irb(main):002:1> def y
irb(main):003:2> puts "z"
irb(main):004:2> end
irb(main):005:1> self
irb(main):006:1> end
=> X
The class definition returns the result of the last statement, so you
can put 'self' just before the end of the definition to get it to return
the class. It's returning nil because def returns nil.


Florian Frank

7/14/2005 11:16:00 PM

0

Robert Klemme wrote:

> A disadvantage of the latter approach is that you cannot define
> methods that receive a block. There is no equivalent (yet) for "def
> foo(&b) b.call(1) end" with define_method, because you cannot do
> define_method(:foo) {|&b| b.call(1)}.

(flori@lambda:~ 0)$ irb
irb(main):001:0> A = Class.new { define_method(:foo) {|&b| b.call(1)} }
=> A
irb(main):002:0> A.new.foo { |x| 2 * x }
=> 2
irb(main):003:0> RUBY_VERSION
=> "1.9.0"

--
Florian Frank



Daniel Brockman

7/15/2005 1:44:00 AM

0

Daniel Brockman

7/15/2005 2:02:00 AM

0

Florian Groß

7/15/2005 1:18:00 PM

0