Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #2181
| From | Stefano Crocco <stefano.crocco@alice.it> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: Using variables in modules |
| Date | 2011-04-03 01:39 -0500 |
| Organization | Service de news de lacave.net |
| Message-ID | <4D498EF305127BBA@smtp209.alice.it> (permalink) |
| References | <1301790250.3173.40.camel@AMD64X2.fritz.box> <1301792211.3173.46.camel@AMD64X2.fritz.box> |
On Sunday 03 April 2011 09:57:05 Stefan Salewski wrote:
> On Sun, 2011-04-03 at 09:30 +0900, Stefan Salewski wrote:
> > Can I define a variable in a module, and access and redefine it later?
>
> OK, this is very close to my desire:
>
> module Gravity
>
> #def initialize()
> @g = 9.81
> #end
>
> def self.get()
> @g
> end
>
> def self.set(g)
> @g = g
> end
>
> end
>
> puts Gravity::get()
>
> Gravity.set(9.8102) # we have done a more precice measurement
>
> puts Gravity.get()
>
> This gives output
> stefan@AMD64X2 ~/pet $ ruby hhh.rb
> 9.81
> 9.8102
>
> Is there something like attr_accessor for modules, allowing writing
> something like g=9.8102 and puts g instead of set and get methods?
You don't need to use attr_accessor or attr_writer to define methods ending
with an =:
module Gravity
@g = 9.81
def self.g= value
@g = value
end
def self.g
@g
end
end
If you want to use attr_accessor, you'll need to do so from the singleton
class of Gravity:
module Gravity
class << self
attr_accessor :g
end
end
I hope this helps
Stefano
Back to comp.lang.ruby | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Using variables in modules Stefan Salewski <mail@ssalewski.de> - 2011-04-02 19:30 -0500
Re: Using variables in modules Stefan Salewski <mail@ssalewski.de> - 2011-04-02 19:57 -0500
Re: Using variables in modules Stefano Crocco <stefano.crocco@alice.it> - 2011-04-03 01:39 -0500
Re: Using variables in modules Brian Candler <b.candler@pobox.com> - 2011-04-03 02:55 -0500
Re: Using variables in modules spiralofhope <spiralofhope_rubyml@lavabit.com> - 2011-04-03 12:37 -0500
Re: Using variables in modules Stefan Salewski <mail@ssalewski.de> - 2011-04-03 15:29 -0500
Re: Using variables in modules Brian Candler <b.candler@pobox.com> - 2011-04-03 15:30 -0500
csiph-web