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