我使用的是Ruby on Rails 3.0.9,并且我试图“动态”设置一些变量值。那是..。
..。在我的模型文件中,我有:
attr_accessor :variable1, :variable2, :variable3
# The 'attributes' argument contains one or more symbols which name is equal to
# one or more of the 'attr_accessor' symbols.
def set_variables(*attributes)
# Here I should set to 'true' all ":variable<N>" attributes passed as symbol
# in the 'attributes' array, but variable names should be interpolated in a
# string.
#
# For example, I should set something like "prefix_#{':variable1'.to_s}_suffix".
end
如何将这些变量值设置为 true
**?**
我尝试使用self.send(...)
方法,但没有成功(但是,我可能根本不知道如何使用那个send
方法……是否可以使用send
方法来处理我需要的内容?!)。
发布于 2011-08-16 22:00:38
attr_accessor :variable1, :variable2, :variable3
def set_variables(*attributes)
attributes.each {|attribute| self.send("#{attribute}=", true)}
end
发布于 2012-10-27 06:10:51
以下是send
与instance_variable_set
的基准测试比较
require 'benchmark'
class Test
VAR_NAME = '@foo'
ATTR_NAME = :foo
attr_accessor ATTR_NAME
def set_by_send i
send("#{ATTR_NAME}=", i)
end
def set_by_instance_variable_set i
instance_variable_set(VAR_NAME, i)
end
end
test = Test.new
Benchmark.bm do |x|
x.report('send ') do
1_000_000.times do |i|
test.set_by_send i
end
end
x.report('instance_variable_set') do
1_000_000.times do |i|
test.set_by_instance_variable_set i
end
end
end
并且计时是:
user system total real
send 1.000000 0.020000 1.020000 ( 1.025247)
instance_variable_set 0.370000 0.000000 0.370000 ( 0.377150)
(使用1.9.2测量)
应该注意的是,只有在某些情况下(像这种情况,访问器是用attr_accessor
定义的),send
和instance_variable_set
在功能上是等价的。如果所涉及的访问器中有一些逻辑,那么就会有所不同,您必须决定需要这两个变量中的哪一个变量。instance_variable_set
只是设置ivar,而send
实际上执行访问器方法,无论它做什么。
另一个备注-这两个方法在另一个方面的行为不同:如果你instance_variable_set
一个还不存在的ivar,它将被创建。如果您使用send
调用一个不存在的访问器,则会引发异常。
发布于 2011-08-16 21:57:19
你想要的方法是instance_variable_set
,所以在你的例子中:
def set_variables(*attributes)
attributes.each {|attribute| self.instance_variable_set(attribute, true)}
end
https://stackoverflow.com/questions/7079222
复制相似问题