Ruby 中的各种变量(local/instance/class/global variable and assignment method)

来源:互联网 发布:同花顺扩展数据管理器 编辑:程序博客网 时间:2024/05/16 04:49

从注释中可以看出每段代码中使用的变量类型

# local variable10.times{ |i| print("=")}puts("local variable")1.times do  a = 1  b = "a"  puts "local variables in the block: #{local_variables.join ", "}"endputs "no local variables outside the block" if local_variables.empty?# instance variable10.times{ |i| print("=")}puts("instance variable")class C  def initialize(value)    @instance_variable = value  end  def value    @instance_variable  endendobject1 = C.new "some value"object2 = C.new "other value"p object1.value # prints "some value"p object2.value # prints "other value"#class variable10.times{ |i| print("=")}puts("class variable")class A  @@class_variable = 0  def value    @@class_variable  end  def update    @@class_variable = @@class_variable + 1  endendclass B < A  def update    @@class_variable = @@class_variable + 2  endenda = A.newb = B.newputs "A value: #{a.value}" #0puts "B value: #{b.value}" #0puts "update A"a.updateputs "A value: #{a.value}"puts "B value: #{b.value}"puts "update B"b.updateputs "A value: #{a.value}"puts "B value: #{b.value}"puts "update A"a.updateputs "A value: #{a.value}"puts "B value: #{b.value}"#global variable10.times{ |i| print("=")}puts("global variable")$global = 0class E  puts "in a class: #{$global}"  def my_method    puts "in a method: #{$global}"    $global = $global + 1    $other_global = 3  endendE.new.my_methodputs "at top-level, $global: #{$global}, $other_global: #{$other_global}"# Assignment method10.times{ |i| print("=")}puts("Assignment method")class F  @value  attr_accessor :value  def my_method    #self.value = 42    @value = 42;     puts "local_variables: #{local_variables.join ", "}"    puts "@value: #{@value.inspect}"  endendF.new.my_method
0 0