【问题标题】:Push element to dynamic array (created with instance_variable_set) in Rails在 Rails 中将元素推送到动态数组(使用 instance_variable_set 创建)
【发布时间】:2017-10-23 19:16:52
【问题描述】:

我有一个属性列表。每个属性都将设置为一个空数组,我想将元素推送到每个数组。

我想出了如何使用instance_variable_set 创建一个动态数组,但我无法向其中推送元素。

这就是我所做的:

attributes = ["eye","hair_color","hair_size","hair_type"]
i = 0
attributes.each do |a|
    # Dynamic arrays are created, like: @eye = []
    instance_variable_set("@#{a}", [])
    # My attempt to push element
    "@#{a}".push(i)
    i += 1
end

如何将元素推送到这些动态数组?

【问题讨论】:

    标签: ruby-on-rails arrays ruby


    【解决方案1】:

    instance_variable_get("@#{a}").push(i) 可以工作

    【讨论】:

      【解决方案2】:

      Petr Balaban 说得对。我想我还会注意到您可以使用each_with_index 而不是手动设置和递增i

      attributes = ["eye","hair_color","hair_size","hair_type"]
      
      attributes.each_with_index do |a,i|
        # Dynamic arrays are created, like: @eye = []
        instance_variable_set("@#{a}", [])
        # As Petr noted...
        instance_variable_get("@#{a}").push(i)
      end
      

      【讨论】:

        【解决方案3】:

        另一种方法是:

        attributes = %w|eye hair_color hair_size hair_type|
        attributes.each_with_index do |a, idx|
          self.class.send :attr_accessor, a.to_sym
          public_send "#{a}=", idx
          (public_send a) << idx
        end
        

        现在您可以通过 getter 访问这些变量:

        hair_size
        #⇒ 2
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-07
          • 1970-01-01
          • 1970-01-01
          • 2014-04-16
          • 2018-02-28
          • 2015-09-14
          • 1970-01-01
          相关资源
          最近更新 更多