一切都在问题中说明。这两种方法都可以通过使用它们的代号来访问(读/写)实例变量:
__send__
instance_variable_set
instance_variable_get
有人可以通过例子来解释吗?
当我们用抽象来探索元编程时,它有时会融化我们的大脑。
=== 编辑 ===
好的,如果我的大脑再次融化,我将答案作为示例供以后使用。
类声明:
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
def full_name
@first_name + ' ' + @last_name
end
end
初始化:
actor = Person.new('Donald', "Duck")
=> #<Person:0xa245554 @first_name="Donald", @last_name="Duck">
发送(读取)的用法:
actor.send('first_name')
=> "Donald"
actor.send(:first_name)
=> "Donald"
actor.send("last_name")
=> "Duck"
actor.send(:last_name)
=> "Duck"
actor.send('full_name')
=> "Donald Duck"
actor.send(:full_name)
=> "Donald Duck"
instance_variable_get 的用法(读取)
actor.instance_variable_get('@first_name')
=> "Donald"
actor.instance_variable_get(:@first_name)
=> "Donald"
actor.instance_variable_get('@last_name')
=> "Duck"
actor.instance_variable_get(:@last_name)
=> "Duck"
发送(写入)的用法:
actor.send('first_name=', 'Daisy')
actor.send('full_name')
=> "Daisy Duck"
actor.send(:first_name=, "Fifi")
actor.send("full_name")
=> "Fifi Duck"
instance_variable_set 的用法(写入)
actor.instance_variable_set('@first_name', 'Pluto')
actor.send("full_name")
=> "Pluto Duck"
actor.instance_variable_set(:@last_name, 'Dog')
actor.send(:full_name)
=> "Pluto Dog"
instance_variable_get 的错误用法(读取)
actor.instance_variable_get('full_name')
#NameError: `full_name' is not allowed as an instance variable name
actor.instance_variable_get('last_name')
#NameError: `last_name' is not allowed as an instance variable name
我对 Rails ActiveRecord 及其关联感到困惑。
感谢您的回答!