首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何设置“动态”变量值?

如何设置“动态”变量值?
EN

Stack Overflow用户
提问于 2011-08-16 21:51:45
回答 5查看 19.4K关注 0票数 21

我使用的是Ruby on Rails 3.0.9,并且我试图“动态”设置一些变量值。那是..。

..。在我的模型文件中,我有:

代码语言:javascript
复制
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方法来处理我需要的内容?!)。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-08-16 22:00:38

代码语言:javascript
复制
attr_accessor :variable1, :variable2, :variable3

def set_variables(*attributes)
  attributes.each {|attribute| self.send("#{attribute}=", true)}
end
票数 63
EN

Stack Overflow用户

发布于 2012-10-27 06:10:51

以下是sendinstance_variable_set的基准测试比较

代码语言:javascript
复制
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

并且计时是:

代码语言:javascript
复制
      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定义的),sendinstance_variable_set在功能上是等价的。如果所涉及的访问器中有一些逻辑,那么就会有所不同,您必须决定需要这两个变量中的哪一个变量。instance_variable_set只是设置ivar,而send实际上执行访问器方法,无论它做什么。

另一个备注-这两个方法在另一个方面的行为不同:如果你instance_variable_set一个还不存在的ivar,它将被创建。如果您使用send调用一个不存在的访问器,则会引发异常。

票数 9
EN

Stack Overflow用户

发布于 2011-08-16 21:57:19

你想要的方法是instance_variable_set,所以在你的例子中:

代码语言:javascript
复制
def set_variables(*attributes)
  attributes.each {|attribute| self.instance_variable_set(attribute, true)}
end
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7079222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档