ruby 访问静态变量 [英] ruby access static variable

查看:35
本文介绍了ruby 访问静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A
  @@ololo = 1
end

A::ololo
A.new.ololo
NoMethodError: undefined method `ololo'

好的.我需要一个 attr_reader

okey. I need an attr_reader

class B
  @@ololo = 1
  attr_reader :ololo
end

A::ololo
NoMethodError: undefined method `ololo'
A.new.ololo
=> nil

哇?ruby 访问器是否有任何限制?

wtf? is there any limit for ruby accessors?

class C
  @@ololo = 1
  def self.ololo
    @@ololo
  end
  def ololo
    @@ololo
  end
end

C::ololo
=> 1
C.new.ololo
=> 1

红宝石男人通常会说是的!非常好!".这很好吗?谁能提供更短的代码?

Ruby men usually say "yeah! pretty good!". is this pretty good? Can anyone provide shorter code?

推荐答案

你不能做你想做的事 :)

You can't do what you want to do :)

@harald 是对的.attr_reader 只会为实例变量定义 GETTER,对于静态"(又名类变量")你需要自己定义 setter 和 getter:

@harald is right. attr_reader will define GETTER only for instance variable, for "static" (aka "class variables") you need to define setter and getter by yourself:

class A
  @@ololo = 1

  # instance level

  # getter
  def ololo
    @@ololo
  end
  # setter
  def ololo=trololo
    @@ololo = trololo
  end

  # and class level
  # if you need it

  # getter
  def self.ololo
    @@ololo
  end
  # setter
  def self.ololo=trololo
    @@ololo = trololo
  end
end

所以:

a = A.new
b = A.new
A.ololo
#=> 1
a.ololo
#=> 1
A.ololo = 100
A.ololo
#=> 100
a.ololo
#=> 100
b.ololo
#=> 100
a.ololo = 4
A.ololo
#=> 4

...

较短的一个:

class A
  @ololo = 1
  class << self
    attr_accessor :ololo
  end
end

这篇关于ruby 访问静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆