Variables y Constantes

Existen métodos para listar los nombres (como cadenas) de

~/chapter8ReflectionandMetaprogramming$ cat -n variablesAndConstants.rb 
 1  class Tutu
 2    def initialize(x,y); @x, @y = x, y; end
 3    @@classvar = 1
 4    ORIGIN = Tutu.new(0, 0)
 5  end
 6  
 7  puts "Globals variables with 'D': "
 8  puts("  "+global_variables.select { |w| w =~/D/ }.inspect) #  [:$KCODE, :$LOAD_PATH, :$LOADED_FEATURES, :$DEBUG]
 9  x = 1
10  puts "Local variables:"
11  puts "  #{local_variables.inspect}" # [:x]
12  
13  puts "Instance variable names: "
14  Tutu::ORIGIN.instance_variables.each { |v|
15    puts "  #{v}"                     #   @x @y
16  }
17  puts "Class variables names: "
18  Tutu.class_variables.each { |v|
19    puts "  #{v}"                     # @@classvar
20  }
21  puts "Constant names: "
22  Tutu.constants.each { |c|
23    puts "  #{c}"                     # ORIGIN
24  }
Ejecución:
~/chapter8ReflectionandMetaprogramming$ ruby variablesAndConstants.rb 
Globals variables with 'D': 
  ["$KCODE", "$LOAD_PATH", "$DEBUG", "$LOADED_FEATURES"]
Local variables:
  ["x"]
Instance variable names: 
  @x
  @y
Class variables names: 
  @@classvar
Constant names: 
  ORIGIN



Subsecciones
Casiano Rodriguez León 2015-01-07