【问题标题】:Is it possible to insert one variable's value into the name of another variable?是否可以将一个变量的值插入另一个变量的名称中?
【发布时间】:2016-02-13 01:00:49
【问题描述】:

假设我有一个循环重复 1000 次。

在循环之前,我设置了 1000 个变量,如下所示:

@n1 = "blabla"
@n2 = "blabla"
@n3 = "blabla"
@n4 = "blabla"
...

我还有一个变量@count,它计算循环所在的迭代,即。它从 1 开始,每个循环增加 1。 我想要做的是打印@n1 if @count = 1,打印@n2 if @count = 2,等等。换句话说,我希望 ruby​​ 使用 @count 的值来决定使用哪个 @n_ 变量。我不想使用条件语句,因为我需要 1000 个。 p>

类似这样的:

@count = 1
if @count < 1001
  puts @("n + @count")
  @count = @count + 1
end

有没有办法做到这一点?

【问题讨论】:

  • 是的,这是可能的,但这是一个糟糕的设计选择。请改用数组或哈希。
  • 一旦你将这 1000 个字符串移动到一个数组中,你就可以写 array.each { |string| puts string }(或者干脆 puts array

标签: ruby-on-rails ruby variables


【解决方案1】:

假设您有一个名为 foo 的实例,其中包含一千个实例变量,可以循环遍历它们:

foo.instance_variables.each do |v| 
  p foo.instance_variable_get(v) 
end

也就是说,您也可以使用字符串名称来获取它们:

1000.times do |count|
  p foo.instance_variable_get("@n#{count}") 
end

【讨论】:

    【解决方案2】:

    是的,您可以这样做:

    if @count < 1001
      instance_variable_set("@#{@count}", @count + 1)
    end
    

    存储在哈希中会更惯用,例如

    h = {}
    if @count < 1001
      h[@count] = @count + 1
    end
    

    【讨论】:

      【解决方案3】:

      虽然您可以使用 instance_variable_get 之类的东西,但您通常会使用数组或散列来存储字符串:

      n = ["blabla", "blabla", "blabla", ... ]
      
      count = 0
      if count < 1000
        puts n[count]
        count += 1
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多