[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Syntax-question: Difference between {...} and do... end?

michael.lesniak@gmail.com

6/15/2006 9:11:00 PM

Hello,

I thought the difference between do...end and {...} is only
syntactical, but:

--- code ---
class Object
# For each instance of Object,
# -> for each thing in ruby,
# a method is defined.
def metaclass
class << self
self
end
end

# Executes in the context of
# an instance of something
def meta_eval &blk
metaclass.instance_eval &blk
end


# Adds methods to a metaclass,
# i.e. the instantiated object
# itself
def meta_def name, &blk
meta_eval do
define_method(name, &blk)
end
end
end
--- end ---

The code

a = "foo"
a.meta_def :foo do puts "hi" end
a.foo

functions, but

a = "foo"
a.meta_def :foo { puts "hi" }

does not (even tried different styles, e.g. putting some komma in,
etc...)

A bit stuck but thankful for the ruby community for the answers given
so far,
Michael

3 Answers

Marcin Mielzynski

6/15/2006 9:45:00 PM

0

Michael Lesniak wrote:

> The code
>
> a = "foo"
> a.meta_def :foo do puts "hi" end
> a.foo
>
> functions, but
>
> a = "foo"
> a.meta_def :foo { puts "hi" }
>
> does not (even tried different styles, e.g. putting some komma in,
> etc...)
>
> A bit stuck but thankful for the ruby community for the answers given
> so far,
> Michael
>

{...} and do..end are introduced mainly because parens in Ruby are
optional. {} binds tighter that do/end. This becomes more obvious with
some examples:

def meth arg,&blk
end

meth "some arg" do
end

-> block applied to method

meth arg {}

-> block applied to arg (which can be a method call)

this can be forced with parens:

meth(arg){
}

-> applied to method and in this case is equivalent to:

meth(arg) do
end

lopex






def

user@domain.invalid

6/16/2006 9:25:00 AM

0

le 15/06/2006 23:11, Michael Lesniak nous a dit:
> Hello,
>
> I thought the difference between do...end and {...} is only
> syntactical, but:
>
> --- code ---
> class Object
> # For each instance of Object,
> # -> for each thing in ruby,
> # a method is defined.
> def metaclass
> class << self
> self
> end
> end
>

I'm new to ruby and I still don't understand statements like
class << self
self
end

Someboby can help me ?

Thank you

Marcin Mielzynski

6/16/2006 1:02:00 PM

0

Zouplaz wrote:

> I'm new to ruby and I still don't understand statements like
> class << self
> self
> end
>
> Someboby can help me ?
>
> Thank you

http://www.whytheluckystiff.net/articles/seeingMetaclassesCl...

lopex