Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

1 view
Skip to first unread message

Michael Lesniak

unread,
Jun 15, 2006, 5:11:23 PM6/15/06
to
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

Marcin Mielżyński

unread,
Jun 15, 2006, 5:44:35 PM6/15/06
to
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

Zouplaz

unread,
Jun 16, 2006, 5:25:17 AM6/16/06
to
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 Mielżyński

unread,
Jun 16, 2006, 9:01:33 AM6/16/06
to
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/seeingMetaclassesClearly.html

lopex

0 new messages