ruby 红宝石scopes.rb

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 红宝石scopes.rb相关的知识,希望对你有一定的参考价值。

class MyGlobal
  $s = 4
end
=> 4

$s
=> 4

$s = 7
 => 7
$s
 => 7
 
 
class MyGlobals
  def c
    $s = 12
  end
end
 => :c
 
$s
 => 7

MyGlobals.new.c
 => 12
 
$s

=> 12
# Class variables with @ are accessible from class methods!
class MyClass
  @var = 2
  
  def self.square
    @var *= @var
  end
end
 
MyClass.square
=> 4

MyClass.square
=> 16
# class variables has to be defined using @@.

class MyClass
  @var = 2
  
  def square
    @var *= @var
  end
end
 
s = MyClass.new
s.var
=> NoMethodError: undefined method `var'
 
s.square
=> NoMethodError: undefined method `*' for nil:NilClass
class MyClass
  @@var = 2
  def square
    @@var *= @@var
  end
  
  def var
    @@var
  end
end

s = MyClass.new
s.var
=> 2

s.square
=> 4

s.var
=> 4

c = MyClass.new
=> 4

c.square
=> 16

c.var
=> 16

s.var
=> 16

MyClass.y
=> exception NoMethodError

s.y
=> exception NoMethodError

以上是关于ruby 红宝石scopes.rb的主要内容,如果未能解决你的问题,请参考以下文章

科普红宝石 Ruby

红宝石ruby

红宝石Ruby

ruby rails3创建自己的红宝石宝石

ruby,红宝石戒指到货

ruby 由红宝石轻松看门狗