ruby access static variable

2020-07-23 04:59发布

class A
  @@ololo = 1
end

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

okey. I need an attr_reader

class B
  @@ololo = 1
  attr_reader :ololo
end

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

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?

标签: ruby syntax
3条回答
迷人小祖宗
2楼-- · 2020-07-23 05:36

Yes, you can.

class A
  cattr_accessor :ololo    
  @@ololo = 1
end

class B
  A.ololo #Gets class variable "ololo" from class A
end

This is basically a Ruby on Rails feature. However, outside Rails, you can obtain the functionality from the Ruby Facets gem:

https://github.com/rubyworks/facets/blob/master/lib/core-uncommon/facets/module/cattr.rb

See this discussion: cattr_accessor outside of rails

查看更多
在下西门庆
3楼-- · 2020-07-23 05:47

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

@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

So:

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

...

Shorter one:

class A
  @ololo = 1
  class << self
    attr_accessor :ololo
  end
end
查看更多
Deceive 欺骗
4楼-- · 2020-07-23 05:52

attr_accessor :ololo defines the methods ololo and ololo= which work against an instance variable named @ololo. So what happens when you try to access A::ololo ruby will find your instance method ololo and fail since you're trying to call it as a class method.

查看更多
登录 后发表回答