Something inconsistent in ruby syntax?

Please take a look at some exemplary code first.

class MailTruck
instance_eval <<-EOS
define_method(:hello1) {puts “hello1”}
EOS

define_method(:hello2) {puts "hello2"}

instance_eval <<-EOS
	def hello3
		puts "hello3"
	end
EOS

def hello4
		puts "hello4"
end

end

hello1 and hello2 are instance methods.
hello3 is a class method.
hello4 is a instance method.

Why hello1 and hello2 are same, but hello3 and hello4 are different?

It seems a little inconsistent . Somebody can give a clear explanation?
Thanks in advance.

uncutstone

On Jun 11, 2006, at 11:10 PM, uncutstone wu wrote:

uncutstone
hello1, hello2, and hello4 are all equivalent. They are the same
thing as writing

class A
def hello1

end

def hello2

end

def hello4

end
end

For hello3 you’ve done the equivalent of

class A
def self.hello3

end
end

The reason doesn’t happen with hello1 is

instance_eval { # self is MailTruck in this block
define_method(…) { … } # this is like self.define_method(…)
{ … }
# since define_method is a method,
# which is the same as define_method
outside of the instance_eval in this case

Logan C. wrote:

The reason doesn’t happen with hello1 is

instance_eval { # self is MailTruck in this block
define_method(…) { … } # this is like self.define_method(…)
{ … }
# since define_method is a method,
# which is the same as define_method
outside of the instance_eval in this case

So I can say the reason is that define_method is a method and def isn’t
a method but a reserved keyword.

Thanks for your explanation, I think I’ve got it now.

uncutstone

On 6/12/06, uncutstone wu [email protected] wrote:

    instance_eval <<-EOS

hello1 and hello2 are instance methods.
hello3 is a class method.

I am as surprised as you are and I could not find any hint in the
documentation why it should be?
instance_eval is an equivalent to self.instance_eval, I fail to see
any
reason why the method definition is
evaluated as a class method.

Can anyone explain while instance_eval without a receiver could change
the
context of self?

Ty in advance

Robert

hello4 is a instance method.

Why hello1 and hello2 are same, but hello3 and hello4 are different?

It seems a little inconsistent . Somebody can give a clear explanation?
Thanks in advance.

I agree

Robert

uncutstone


Posted via http://www.ruby-forum.com/.


Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.

  • Albert Einstein