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

M

Michael Lesniak

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
 
M

Marcin Mielżyński

Michael said:
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
 
Z

Zouplaz

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,216
Latest member
topweb3twitterchannels

Latest Threads

Top