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

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

# local variable
10.times{ |i| print("=")}
puts("local variable")
1.times do
  a = 1
  b = "a"
  puts "local variables in the block: #{local_variables.join ", "}"
end

puts "no local variables outside the block" if local_variables.empty?

# instance variable
10.times{ |i| print("=")}
puts("instance variable")
class C
  def initialize(value)
    @instance_variable = value
  end

  def value
    @instance_variable
  end
end

object1 = C.new "some value"
object2 = C.new "other value"

p object1.value # prints "some value"
p object2.value # prints "other value"

#class variable
10.times{ |i| print("=")}
puts("class variable")
class A
  @@class_variable = 0

  def value
    @@class_variable
  end

  def update
    @@class_variable = @@class_variable + 1
  end
end

class B < A
  def update
    @@class_variable = @@class_variable + 2
  end
end

a = A.new
b = B.new

puts "A value: #{a.value}" #0
puts "B value: #{b.value}" #0

puts "update A"
a.update

puts "A value: #{a.value}"
puts "B value: #{b.value}"

puts "update B"
b.update

puts "A value: #{a.value}"
puts "B value: #{b.value}"

puts "update A"
a.update

puts "A value: #{a.value}"
puts "B value: #{b.value}"

#global variable
10.times{ |i| print("=")}
puts("global variable")
$global = 0

class E
  puts "in a class: #{$global}"

  def my_method
    puts "in a method: #{$global}"

    $global = $global + 1
    $other_global = 3
  end
end

E.new.my_method

puts "at top-level, $global: #{$global}, $other_global: #{$other_global}"

# Assignment method
10.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}"
  end
end

F.new.my_method