简体   繁体   中英

Why does instance_eval handle direct accessors in a special way?

Why does the following code not raise an error:

Object.new.instance_eval { some_accessor_that_does_not_exist= "a value" }

While the following would raise a NameError as you would expect:

Object.new.instance_eval { some_method_that_doesnt_exist }

Even this would raise an error:

Object.new.instance_eval { self.some_accessor_that_does_not_exist= "a value" }

I've tried this on 1.8.7-p352 as well as 1.9.3-p194 with the same result.

Object.new.instance_eval { some_accessor_that_does_not_exist= "a value" }

This is interpreted as a creation of new local var named some_accessor_that_does_not_exist , not a setter invocation. When you use assignments with implicit receiver, ruby can't know if you wanted to create a local var or call a method, because there's no special syntax for declaring local vars. And so it creates a local var.

But when you use explicit receiver ( self.some_accessor_that_does_not_exist ), then ruby interprets it as a method and fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM