如何在main中动态创建局部变量

时间:2016-11-11 21:11:27

标签: ruby

如何在普通ruby文件的主绑定中定义变量?

我尝试过TOPLEVEL_BINDING,但它不会将变量共享到主范围

        <div class="form-group">
                    <div class="md-col-4"><label> MileStone Date</label>                </div>
                    <div class="md-col-4">
                                         <ng-dropdown 
              [dataSourceList]="mileStonedataSourceList" 
               [(ngModel)]="selectedMileStone" 
                [ngModelOptions]="{standalone: true}"  
           (onSelectItem)="onMileStoneSelect($event)"  
           ngDefaultControl></ng-dropdown>
      </div>
     </div>

1 个答案:

答案 0 :(得分:1)

您可以动态定义实例变量:

5.times do |i|
  instance_variable_set(:"@reader#{i}", "library_name#{i}")
  instance_variable_set(:"@book#{i}", "book_title#{i}")
end

puts @reader1
puts @book1
puts @book4

# => library_name1
#    book_title1
#    book_title4

另一种可能性是使用method_missing伪造局部变量,同时使用实例变量作为缓存:

def create_variable_or_use_cache(name, &block)
  name = "@#{name}"
  instance_variable_get(name) || instance_variable_set(name, block.yield)
end

def method_missing(sym,*p)
  if sym=~/^reader(\d+)$/ then
    create_variable_or_use_cache(sym){ "Create reader#{$1} here" }
  elsif sym=~/^book(\d+)$/ then
    create_variable_or_use_cache(sym){ "Create book#{$1} here" }
  else
    super
  end
end

puts reader1
puts reader1
puts book3
wrong_method

# => 
# Create reader1 here
# Create reader1 here
# Create book3 here
# binding.rb:13:in `method_missing': undefined local variable or method   `wrong_method' for main:Object (NameError)

这是一个有趣的Ruby练习,但我不确定你应该使用它。