3

一切都在问题中说明。这两种方法都可以通过使用它们的代号来访问(读/写)实例变量:

__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 及其关联感到困惑。

感谢您的回答!

4

2 回答 2

2

__send__允许您通过名称/符号调用方法
instance_variable_*,允许您设置/获取实例变量

于 2013-01-23T10:58:00.790 回答
2

__send__方法调用在你的类中定义的方法,如果没有定义方法,那么你不能使用方法,send但是方法会改变实例变量的值,而不需要任何封装方法(如 getter 或 setter)。instance_variable_getset

__send__如果您想调用由符号标识的方法并在需要时传递任何参数,则使用。

例如

class Test
  def sayHello(*args)
    "Hello " + args.join(' ')
  end
end
k = Test.new
k.send :sayHello, "readers"   #=> "Hello readers"

instance_variable_get返回给定实例变量的值,如果未设置实例变量,则返回 nil。使用此方法无需封装

例如

class Test
  def initialize(p1)
    @a = p1
  end
end
test = Test.new('animal')
test.instance_variable_get(:@a)    #=> "animal"

instance_variable_set用于设置实例变量的值,无需封装方法。例如

class Test
  def initialize(p1)
    @a = p1
  end
end
test = Test.new('animal')
test.instance_variable_set(:@a, 'animal')
于 2013-01-23T11:47:40.573 回答