代码之家  ›  专栏  ›  技术社区  ›  poseid

Ruby类集合

  •  0
  • poseid  · 技术社区  · 16 年前

    这是怎么工作的?

    在IRB中:

    >> class A
    >>   b = [1, 2,3]
    >> end
    => [1, 2, 3]
    

    B是实例变量吗?类变量?我如何从B访问 在班外?是否用于元编程?

    2 回复  |  直到 16 年前
        1
  •  6
  •   sepp2k    16 年前

    B是实例变量吗?类变量?

    不,它是 class ... end 范围。

    我怎样才能从班外访问B?

    你不会的。一旦它到达 end .

    是否用于元编程?

    可以。例子:

    class A
      b = [1,2,3]
      b.each do |i|
        define_method("foo#{i}") do end
      end
    end
    

    我已经定义了方法foo1、foo2和foo3。

    当然,如果我不创建变量b,只创建了它,那么它的行为就不会有任何不同。 [1,2,3].each 直接。因此,单独创建局部变量本身并没有什么作用,它允许您编写更干净的代码(与在方法中使用局部变量相同)。

        2
  •  1
  •   Cicatrice    16 年前

    B是一个简单的 变量,您不能从块外部访问它。

    您可以使用如下类:

    class Building
      @@count=0                        #This is a class variable
      MIN_HEIGHT=50                    #This is a constant
      attr_accessor :color, :size      #grant access to instance variables
      def initialize options
        @color=options[:color]         #@color is an instance variable
        @size=options[:size]           #@size too
        @@count=@@count+1
      end
    
      def self.build options           #This is a class method
        # Adding a new building
        building=Building.new options
      end
    end
    #[...]
    Building.build({:color=>'red', :size=>135})
    blue_building=Building.new({:color=>'blue', :size=>55})
    puts blue_building.color          # How to use an instance variable
    #                          => 'blue'
    puts "You own  #{Building.count.to_s} buildings !"     # How to use a class variable
    #                          => 'You own 2 buildings !'
    puts Building::MIN_HEIGHT          # How to use a constant
    #                          => 50
    
    推荐文章